API 封装(axios)

import axios from "axios";
import { message } from 'antd';
let request = axios.create({
    headers: {
        'Content-Type': 'application/json; charset=utf-8',
    }
})
// url
request.defaults.baseURL = process.env.REACT_APP_BASE_URL;
const formatRequestParams = (params: any) => {
  if (params && params !== {}) {
    const obj = Object.keys(params).reduce((previousValue, currentValue) => {
      if (!params[currentValue]) {
        return {
          ...previousValue,
          [currentValue]: params[currentValue]
        }
      }
      return previousValue
    }, {})
    return obj
  }
  return params
}
request.interceptors.request.use(
    config => {
        if (config.dataType !== 'form') {
            config.data = JSON.stringify(config.data);
        }
        const formatParams = formatRequestParams(config.params)
        const newConfg = {
            ...config,
            headers: {
                ...config.headers,
                'X-Token': localStorage.getItem('token')
            },
            params: formatParams,
            postData: {
                ...config.postData,
            }
        };
        return newConfg;
    },
    err => {
        return Promise.reject(err)
    })

request.interceptors.response.use(function (response) {
    const { data, headers } = response;
    return headers['content-type'] === "application/octet-stream" ? response : data
}, function (error) {
    const status = error?.response?.status;
    if (status === 417) {
    // 业务场景,各自发挥
        window.alert('Your token is expired, please login again')
    }
    const data = error?.response?.data;
    const msg = data?.error?.msg;
    message.error(msg)
    return Promise.resolve({
        data: [],
        paging: {},
        error: true,
        response: error?.response || {},
    });
});
export default request;

你可能感兴趣的:(API 封装(axios))