axios常用操作


axios常用操作

一:函数化编程

1:编写可复用的方法

axios(config)的方法中,有必须的url参数和非必须的options参数。所以我们可以先写一个接受这两个参数的方法,在这个方法中我们可以添加一些业务化的代码,例如修改headers中的一些参数。

function request(url, options) {
  const defaultOptions = {
    credentials: 'include',
  };
  const newOptions = { ...defaultOptions, ...options };
  newOptions.headers = {
    ...newOptions.headers,
  };
  if (newOptions.method === 'POST' || newOptions.method === 'PUT') {
    newOptions.headers = {
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=utf-8',
      ...newOptions.headers,
    };
    newOptions.data = JSON.stringify(newOptions.data);
  }

  return axios({ url, ...newOptions })
    .then(checkStatus)
    .then((response) => {
      return response.data;
    })
    .catch((e) => {
      if (status === 403) {
        // 跳转
      }
    });
}

export default request;

然后我们在services文件中调用这个方法:

export async function api() {
  return request('/aa/bb');
}

export async function api2(params) {
  return request('/aa/cc', {
    method: 'PUT',
    data: params,
  });
}

  

 

二:拦截

1:如何在axios拦截时修改headers中的值(例如多语言)

axios.interceptors.request.use(
  (config) => {
    const config2 = config;
    config2.timeout = 30000; //eslint-disable-line
    config2.headers['Accept-language'] = 'USSSSS';
    return config2;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

如果这里直接操作config会报 no-param-reassign (eslint)的错误。

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM