4

I have this API:

            const url = url;
            const headers = new Headers({
                "Content-Type": "application/json",
                "Accept": "application/json", // change to application/javascript for jsonp
                "Access-Control-Allow-Credentials": true,
                "Access-Control-Allow-Origin": true,
                "access_token": accessToken,
                "id_token": idToken,
            });
            const options = {
                method: "GET",
                headers: headers,
                credentials: "same-origin",
                mode: "no-cors"
            };

            fetch(url, options)
            .then(function(response) {
                console.log('-working: ',response.json());
            })
            .catch(function(error) {
                console.log('-error: ',error);
            });

Having the same API on postMan this works like a charm there but on my code I always get 401 (Unauthorized).

Also if I remove "no-cors" I get a 401 plus CORS issue

Dani
  • 3,128
  • 2
  • 43
  • 91
  • Can you show the request details? Are you sure that the `headers` information was sent to the server? – Dherik Jun 21 '18 at 21:04
  • Exactly, that was the problem. I'm sending any headers with `no-cors`. More info: https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers – Dani Jun 22 '18 at 08:50
  • Possible duplicate of [fetch() does not send headers?](https://stackoverflow.com/questions/45591594/fetch-does-not-send-headers) – Dherik Jun 22 '18 at 10:59

2 Answers2

1

I was having the same issue.

My senior said, that CORS is not safe, so first compare the headers of both the requests.

I would suggest you use Wireshark to see the the header that is being sent from both the requests.

Steps(step 3 and 4 is for conveniently spotting your requests):

  1. Install Wireshark.
  2. Select the network connection that you are using for the calls(for eg, select the Wifi if you are using it)
  3. There will be many requests and responses, close extra applications.
  4. Usually the requests are in green color, once you spot your request, copy the destination address and use the filter on top by typing ip.dst==52.187.182.185 by putting the destination address.
  5. Tap on your request made by postman and by your call.
  6. Compare both the headers.

In my case, I was calling the API from my react native app, and the header parameter was getting converted into lowercase automatically. So, to correct it, I made the parameter in lowercase in backend server.

Play "Spot the difference" between the two windows and find yours.

If this doesn't work, go with setting up CORS.

Ritveak
  • 2,930
  • 2
  • 13
  • 28
0

CORS needed to be added as an additional header on the back end

Dani
  • 3,128
  • 2
  • 43
  • 91