msq*_*qar 8 reactjs react-native axios
我正在使用 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');
},
Run Code Online (Sandbox Code Playgroud)
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;
});
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我什至尝试使用 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();
});
});
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?
谢谢。
问题似乎是在实际设置标头之前发送请求。原因是因为setHeader
内部依赖于在实际设置标头之前触发的回调,并且没有钩子允许调用代码在触发请求之前等待此代码完成。
不过它是可以修复的,setHeader
返回 a并用对象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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
然后在标题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');
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
10131 次 |
最近记录: |