在我的 Reactjs 应用程序中,我想添加一个拦截器,它可以将一些 header 附加到一些后端响应
所以,我尝试了这个:
export default function App() {
axios.interceptors.response.use(
(config)=> {
config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
return config;
},
(error) => {
// ON ERREOR
})
......
);
而且我假设我的 header 会附加到每个后端响应中。但这似乎不起作用。
建议??
最佳答案
添加请求拦截器
axios.interceptors.request.use(
config => {
const token = localStorage.getItem('auth_token');
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error)
});
添加响应拦截器
axios.interceptors.response.use((response) => { // block to handle success case
return response
}, function (error) { // block to handle error case
const originalRequest = error.config;
if (error.response.status === 401 && originalRequest.url ===
'http://dummydomain.com/auth/token') { // Added this condition to avoid infinite loop
// Redirect to any unauthorised route to avoid infinite loop...
return Promise.reject(error);
}
if (error.response.status === 401 && !originalRequest._retry) { // Code inside this block will refresh the auth token
originalRequest._retry = true;
const refreshToken = 'xxxxxxxxxx'; // Write the logic or call here the function which is having the login to refresh the token.
return axios.post('/auth/token',
{
"refresh_token": refreshToken
})
.then(res => {
if (res.status === 201) {
localStorage.setItem('auth_token',res.data);
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('auth_token');
return axios(originalRequest);
}
})
}
return Promise.reject(error);
});
Click here详细查看主题。
关于javascript - 如何使用 Axios 拦截器向响应添加一些 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68714143/