0

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.

Night Fighter
  • 57
  • 1
  • 9

2 Answers2

0

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
} 
Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
  • Your code is okay, now I am getting the token but axios is not working again. Is there a problem with the data types? Or does the expo fail? @Rafael – Night Fighter Jul 31 '20 at 17:32
  • Does it throw an error? Could you try `axios.post('http://localhost/api', data, { headers: { Authorization: 'Bearer '+ token } });` and check if it works ? I removed the back ticks just because of code formatting here – Rafael Tavares Jul 31 '20 at 18:02
  • Hi @Rafael, this code doesn't work either. It just throws `Request failed with status code 403` – Night Fighter Aug 01 '20 at 20:26
  • @NightFighter Are you sure you are sending the body data (`data`) correctly? As you posted in your question, `(data: data)` won't work, but as I did in the comment should work if it is in the correct format. Can you check what you are receiving in the server? – Rafael Tavares Aug 01 '20 at 20:28
  • My body's data type is string. Is this data type correct or should I change it? Server gives `"POST /api HTTP/1.1" 403 42 "-" "okhttp/3.12.1"`. Also with Postman, it is working. – Night Fighter Aug 01 '20 at 21:29
  • If your server expects a string, try adding to axios header `"Content-Type": "text/plain"`. It should look like `{ headers: { Authorization: 'Bearer '+ token, "Content-Type": "text/plain" } }`. Maybe you will need to send body data as `'\"' + data + '\"'`. See [this question](https://stackoverflow.com/q/43573297/8839059) – Rafael Tavares Aug 01 '20 at 21:43
0

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
      },
    });
Night Fighter
  • 57
  • 1
  • 9