Axios 发送了错误的令牌

Axios is sending the wrong token

在 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"
          },
        }
      )

一切正常。它给了成功。

但在 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"
              },
            }
          )

在console.log(token)中,一切似乎都很棒。我可以看到我的令牌。它在 Postman 中也很好用。

根据 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.

因为它 returns 一个 Promise,您应该使用 .then()async/await:

获取令牌
async function doRequest() {
  let token = await AsyncStorage.getItem("token");
  // do request
} 

我想知道以后谁看到这个post axios 没有在React-Native 中发送我的headers。在这种情况下,也许你应该尝试获取。

@Rafael 的回答也很棒

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