1.傳入配置參數(shù)
單次請(qǐng)求
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))
多次請(qǐng)求
//給所有請(qǐng)求添加請(qǐng)求頭
axios.defaults.headers.common['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
//給所有POST請(qǐng)求添加請(qǐng)求頭
axios.defaults.headers.post['Authorization'] = `Bearer ${localStorage.getItem('access_token')}`;
2.創(chuàng)建axios實(shí)例
let reqInstance = axios.create({
headers: {
Authorization : `Bearer ${localStorage.getItem(‘a(chǎn)ccess_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);
}
);
使用攔截器的另一個(gè)好處是可以設(shè)置token過期時(shí)自動(dòng)刷新token:
const refreshToken= ()=>{
// gets new access token
}
// 403請(qǐng)求時(shí)自動(dòng)刷新access token
axios.interceptors.response.use(
response => {
return response;
},
error => {
if(error.response.status == 403){
refreshToken()
}
}
);
Using Axios to set request headers - LogRocket Blog
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者