如何更改axios请求配置



对于每个到后端的请求,我都会发送一个访问令牌。如果令牌没有通过验证,那么我保存原始请求的配置,并请求更新令牌。如果一切正常,那么我会重新发送原始请求。问题是原始请求是使用旧令牌发送的。告诉我如何更新标头中的值。批准

import axios from 'axios'
import { setAccessToken } from '../store/authSlice'
export const axiosConfig = (accessToken: any, dispatch: any) => {
const API_URL = 'http://localhost:3001/api'
const $api = axios.create({
withCredentials: false,
baseURL: API_URL
})
$api.interceptors.request.use((config) => {
config.headers!.Authorization = `Bearer ${accessToken}`
return config
})
$api.interceptors.response.use(
(config) => {
return config
},
async (error) => {
const originalRequest = error.config
if (error.response.status === 403 && error.config && !error.config._isRetry) {
originalRequest._isRetry = true
try {
const response = await axios.get(`${API_URL}/auth/refresh-tokens`, {
withCredentials: false,
headers: {
Authorization: `Bearer ${localStorage.refreshToken}`
}
})
localStorage.setItem('refreshToken', response.data.refreshToken)
dispatch(setAccessToken(response.data.accessToken)) // new token
return $api.request(originalRequest) // <=== original request with old token
} catch (e) {
console.log('error')
}
}
throw error
}
)
return $api
}

您使用的是$api.enterceptors.response.use((,它在响应上,而不是在请求上。您将无法更改已发送请求的授权标头。

如果用户已过期/未登录,我会使用某种类型的错误处理程序或axios响应拦截器将他们引导到登录页面。然后我会有一个错误处理程序函数,可以尝试重新授权,然后让错误处理程序功能重新发送原始请求,然后更新授权令牌。但请记住,您仍然无法更改已发送的请求。

myAxoisInstance.interceptors.request.use(
function (config) {
// This is run on each request so if you have or then update 
the token for local storage your next request will get that updated token

const token = localStorage.getItem("token");
if (token) {
//Assign the token to the config
//If you need to send a request here to see if token is valid I don't recommend that. If you are using a JWT token you can check if it is expired here and do something else like a redirect to login.
config.headers!.Authorization = `Bearer ${token}`;
} else {
//Can retrieve and assign token here I typically like to do a redirect here as they are likely not logged or sesson expired. in or something like that. Then allow the sign-in process to add the token to the local storage.
}
return config;
},
function (error) {
return Promise.reject(error);
}
);

最新更新