当前位置: 首页>后端>正文

使用axios添加请求头的几种方式

1.传入配置参数

单次请求

const config = {
  headers:{
    header1: value1,
    header2: value2
  }
};
const url = "api endpoint";

const data ={
  name: "Jake Taper",
  email: "taperjake@gmail.com"
}
//GET
axios.get(url, config)
  .then(res=> console.log(res))
  .catch(err=> console.log(err))

//POST
axios.post(url, data, config)
  .then(res => console.log(res))
  .catch(err => console.log(err))

多次请求

//给所有请求添加请求头
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;

//给所有POST请求添加请求头
axios.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;

2.创建axios实例

let reqInstance = axios.create({
  headers: {
    Authorization : `Bearer ${localStorage.getItem(‘access_token’)}`
    }
  }
})
reqInstance.get(url);

3.使用axios拦截器

axios.interceptors.request.use(
  config => {
    config.headers['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

使用拦截器的另一个好处是可以设置token过期时自动刷新token:

const refreshToken= ()=>{
  // gets new access token
}

// 403请求时自动刷新access token
axios.interceptors.response.use(
    response => {
        return response;
    },
    error => {
        if(error.response.status == 403){
            refreshToken()
        }
    }
);

Using Axios to set request headers - LogRocket Blog


https://www.xamrdz.com/backend/3z41942677.html

相关文章: