In React, this is working:
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):
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. I can see my token. It also works well in Postman.
According to the docs:
Returns:
Promise
resolving with a string value, if entry exists for givenkey
, ornull
otherwise.
Promise
can also be rejected in case of underlying storage error.
Since it returns a Promise
, you should get the token using .then()
or async/await
:
async function doRequest() {
let token = await AsyncStorage.getItem("token");
// do request
}