我正在使用 Axios
("axios": "^0.19.0")
向后端发出 GET 请求,该请求的工作原理与我已经通过 Postman macOS 应用程序发送相同令牌进行测试一样,并返回正确的用户对象。
但是从我的 React Native 应用程序中,每当我执行 get 请求并传递相同的不记名令牌时,我都会得到最后登录的用户作为响应。
这就是我发送请求的方式:
getUserByToken: function(token) {
var headers = [
{ key: 'Authorization', value: 'Bearer ' + token},
{ key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
{ key: 'Cache-Control', value: 'no-cache'}
];
setHeaders('get', headers);
return AxiosInstance.get('/user');
},
setHeaders 方法用于设置请求的标头,我将所有 http 方法重置为空对象,并为以下请求设置正确的键值。
export const setHeaders = (type, props) => {
AxiosInstance.interceptors.request.use(config => {
config.headers[type] = {};
props.forEach((prop) => {
config.headers[type][prop.key] = prop.value;
});
return config;
});
}
如您所见,我什至尝试使用 Cache-Control: no-cache 但仍然无缘无故地保持缓存。
这就是我从我的
AuthView.js
调用此函数的方式
UserServices.getUserByToken(loginData.access_token)
.then(userResponse => {
// here userResponse is the previous user!
// even though i'm passing the correct token
this.props.onSetUserInfo(userResponse.data);
this.setState({
loading: false
}, () => {
startMainTabs();
});
});
为什么会发生这种情况?
谢谢。
问题似乎是在实际设置标头之前发送请求。原因是因为
setHeader
内部依赖于在实际设置标头之前触发的回调,并且没有钩子允许调用代码在触发请求之前等待此代码完成。
它是可以修复的,让
setHeader
返回 Promise
并使用 config
对象来解析
export const setHeaders = (type, props) => {
return new Promise(resolve => {
AxiosInstance.interceptors.request.use(config => {
config.headers[type] = {};
props.forEach((prop) => {
config.headers[type][prop.key] = prop.value;
});
return resolve(config);
});
});
}
然后在
getUserByToken
、await
标题
getUserByToken: async function (token) {
var headers = [
{ key: 'Authorization', value: 'Bearer ' + token},
{ key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
{ key: 'Cache-Control', value: 'no-cache'}
];
await setHeaders('get', headers);
return AxiosInstance.get('/user');
}
请检查下面的代码,我已经在我的项目中测试了相同的代码,并且工作正常。
getUserByToken: function(token) {
var headers = [
{ key: 'Authorization', value: 'Bearer ' + token},
{ key: 'Content-Type', value: 'application/x-www-form-urlencoded'},
{ key: 'Cache-Control', value: 'no-store'}
];
setHeaders('get', headers);
return AxiosInstance.get('/user');
},
使用上面相同的代码就可以解决你的问题。
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
Authorization: `Bearer ${token}`,
};
const response = await axios({
method: 'post',
data: {name: 'John'},
url: 'https://example.com',
headers
});