简体   繁体   中英

Axios is sending the wrong token

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 given key , or null 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
} 

I want to know whoever sees this post in the future that Axios did not send my headers in React-Native. In such a case, maybe you should try fetch.

@Rafael's answer was also great.

fetch("http://localhost/api", {
      method: "post",
      headers: new Headers({
        "x-auth-token": `${token}`,
        "Content-Type": "application/json",
      }),
      body: {
        body
      },
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM