[英]Axios is sending the wrong token
In React, this is working:在 React 中,这是有效的:
let token = localStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
Everything is ok.一切都好。 It gives success.
它带来成功。
But in React Native (AsyncStorage), it gives wrong token error (403):但是在 React Native (AsyncStorage) 中,它给出了错误的令牌错误 (403):
let token = AsyncStorage.getItem("token");
axios
.post(
`http://localhost/api`,
(data: data),
{
crossdomain: true,
},
{
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "POST",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true"
},
}
)
In console.log(token), everything seems great.在 console.log(token) 中,一切看起来都很棒。 I can see my token.
我可以看到我的令牌。 It also works well in Postman.
它也适用于 Postman。
Returns:
回报:
Promise
resolving with a string value, if entry exists for givenkey
, ornull
otherwise.Promise
使用字符串值解析,如果给定key
存在条目,否则null
。
Promise
can also be rejected in case of underlying storage error.Promise
也可以在底层存储错误的情况下被拒绝。
Since it returns a Promise
, you should get the token using .then()
or async/await
:由于它返回
Promise
,因此您应该使用.then()
或async/await
获取令牌:
async function doRequest() {
let token = await AsyncStorage.getItem("token");
// do request
}
I want to know whoever sees this post in the future that Axios did not send my headers in React-Native.我想知道以后看到这个帖子的人Axios没有在React-Native中发送我的标题。 In such a case, maybe you should try fetch.
在这种情况下,也许你应该尝试 fetch。
@Rafael's answer was also great. @Rafael 的回答也很棒。
fetch("http://localhost/api", {
method: "post",
headers: new Headers({
"x-auth-token": `${token}`,
"Content-Type": "application/json",
}),
body: {
body
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.