我使用了一个Axios拦截器来拦截我的Axios登录请求。但是它也被其他axios请求所使用。是否有一个拦截器意味着它将被所有的axios请求所使用?如果是的话,我怎样才能将它用于特定的请求。在这种情况下,我的登录请求?
Axios.interceptors.response.use(res => {
// console.log(`complete response ---> ${JSON.stringify(res)}`)
// console.log(`This is the login response----> ${JSON.stringify(res.headers)}`)
const authorization = res.headers.authorization;
console.log(`Entering login`);
const bearerToken = authorization.substring(7, authorization.length);
const userLoginResponse: LoginResponse = {
httpStatus: res.status,
token: bearerToken,
user: {
.
.
.
}
}
this.authParams = {
.
.
.
.
}
//console.log(`This is the userLoginResponse ---->${JSON.stringify(userLoginResponse)}`)
this.setObject();
resolve(userLoginResponse)
return res;
}, (error) => {
console.log(`This is the error status ---> ${error.response.status}`)
if (error.response.status === 401) {
resolve(error.response);
}
})
await Axios.post(loginAPIURL, params, config);
这是另一个axios请求:
const submitAPIURL =
process.env.REACT_APP_API_ADD_INITIATIVE_URL ||
"";
axios.post(submitAPIURL, initiative, config).then(submitRes =>{
resolve(submitRes.headers)
}).catch(error => {
reject(error);
})
});
但登录Axios请求的Axios代祷者也被调用为上述请求。
发布于 2020-11-03 23:58:24
是否有一个拦截器意味着它将被所有axios请求使用?
是
如何仅用于特定的请求?
我建议为每种用法创建单独的Axios实例。
例如
const myAuthenticatedApiClient = axios.create({
baseURL: process.env.REACT_APP_API_WHATEVER_URL
})
const myOtherApiClient = axios.create({
baseURL: process.env.REACT_APP_API_ADD_INITIATIVE_URL
})
myAuthenticatedApiClient.interceptors.response.use(res => {
// whatever
})
myAuthenticatedApiClient.post(...) // will use the interceptor
myOtherApiClient.post("", initiative, config) // no interceptor on this one
对于未经身份验证的请求,还可以使用默认的axios
实例。
https://stackoverflow.com/questions/64672337
复制相似问题