Axios封装

Axios封装,第1张

XmlHttpRequest对象XHR

const instance = axios.create({
    baseURL: 'http://www.codeman.ink:3000',		// 这里要带上http:// , 并且有时还要带上 端口号
    timeout: 3000,								// If the request takes longer than `timeout`, the request will be aborted.
    // `withCredentials` indicates whether or not cross-site Access-Control requests should be made using credentials
    withCredentials: true,
  	headers: {'X-Requested-With': 'XMLHttpRequest'}		// `headers` are custom headers to be sent
});

// 也可以这样
instance.defaults.baseURL = 。。。
instance.defaults.withCredentials = 。。。 
instance.defaults.timeout = 。。。

// 不管是post/get/delete/put, 请求头上都会有这个键值对
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;	
// post请求时, 请求头上才会有这个键值对
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
拦截器
// 发请求前执行
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });
  
// 在 then, catch 方法前执行
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

AXIOS 博客园
AXIOS / README
AXIOS官方文档
Intellij IDEA

import axios from 'axios'
// 创建实例
const instance = axios.create({
    timeout:3000,
    withCredentials:true,
    headers:{'Content-Type':'application/json'}
}) 
// 请求拦截
instance.interceptors.request.use(config => {
    console.log(config);
    // 携带 token 去访问
    config.headers.token = localStorage.getItem('token');
    return config;
}, err => {
    console.log(err);
    return Promise.reject(error);
});
// 响应拦截
instance.interceptors.response.use(response => {
    console.log(response);
    return response;
}, err => {
    console.log(err);
    return Promise.reject(error);
});

export default instance;

axios 拦截器

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1324941.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-12
下一篇 2022-06-12

发表评论

登录后才能评论

评论列表(0条)

保存