2

I am trying to get json data returned from my api call using reactjs. 1. I tried running url with valid bearer token on fiddler and it gave me correct results. 2. I tried using same url in below fetch call and used the same fiddler generated bearer token in react code.

It throws 401 unauthorized error.

I compared point 1 and point 2 fiddler requests under tab AUTH. One has correct bearer token but 2nd one i.e react code says "No Authorization Header is present". I am sending Token in react code but why it says "No Authorization Header is present"

componentDidMount () {
  const url = 'my reallyworking api url on fiddler';
  fetch(url
    , {
      method: 'POST',
      crossDomain: true,
      mode: 'no-cors',
      headers: new Headers({
        'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      })
    }
  )
    .then(res => res.json())
    .then(
      (result) => {
        alert('success');
        this.setState({
          isLoaded: true,
          gridData: result.items
        });
      },
      (error) => {
        this.setState({
          isLoaded: true,
          error
        });
      }
    );
}

Fiddler is not showing any Headers. Below is my fiddler tracking

POST https://myurl HTTP/1.1
Host: myHost
Connection: keep-alive
Content-Length: 0
accept: application/json
Origin: https://localhost:xyz
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36
Referer: https://localhost:xyz/testfetch
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9

Note: 1. I created a headers object headers: new Headers({'content-type': 'application/json'}),as explained here 2. I am not using isomorphic fetch as explained here

Kurkula
  • 6,386
  • 27
  • 127
  • 202
  • Maybe try `console.log` your `new Header()` to see if it returns what you expect? Else, using a plain key-value object for your `header` should be fine, as state [in the docs](https://facebook.github.io/react-native/docs/network#making-requests), [or this docs](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options) – wicky Mar 01 '19 at 03:42
  • I tried with plain static key also but no luck. – Kurkula Mar 01 '19 at 05:07
  • Try tracing the header of your fiddler request too, cause not all api takes `"Bearer "` as the prefix for auth – wicky Mar 01 '19 at 05:16
  • tried to track and found no header related information. I edited the question with info. – Kurkula Mar 01 '19 at 21:37
  • Possible duplicate of [How to set the content-type of request header when using Fetch APi](https://stackoverflow.com/questions/38156239/how-to-set-the-content-type-of-request-header-when-using-fetch-api) – Ian Kemp Mar 01 '19 at 21:57
  • 1
    Different framework takes different Auth header. For example, [Django REST Framework](https://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication) takes `"Token "` as the prefix. You should look for what prefix your framework is using – wicky Mar 02 '19 at 08:21
  • 1
    Did you try with adding **credentials:include** in req?? ** fetch(url, { mode: "cors", // no-cors, cors, *same-origin credentials: "include", // include, *same-origin, omit ** – Nithin CV Mar 04 '19 at 02:28
  • wich domains has you or how many? like to domain.name.com and doman.sample.com – Soleil Mar 08 '19 at 17:54

5 Answers5

4

Try to check the API in Postman. That will show detailed request and response to you.

Maneesh
  • 664
  • 5
  • 12
3

A Headers object also has an associated guard, which takes a value of immutable. Why did you use POST without body? Edit your fetch function like:

fetch(url, {
   method: 'POST',
   crossDomain: true,
   mode: 'no-cors',
   body: JSON.stringify({// you data here})
   headers: {
     'Authorization': 'Bearer ' + 'token generated from fiddler after running auth',
     'Accept': 'application/json',
     'Content-Type': 'application/json'
   }
})
  .then(response => response.json())
  .then(responseJson => {
   // do somethign here...
   }
Vu Luu
  • 792
  • 5
  • 16
0

First of all i didnt't find what is the option "crossDomain" mean, official documentation does not contain such option. Secon - i'd try to make such auth request to the local test server and check if all necessary data included, additionally it can be checked in the network tab of the devTools. When you will see what's wrong with request you can make next steps to do at first a simple auth request without additional options.

Alexandr
  • 1
  • 1
0

When you need use CORS, while your domains point same server and allow headers in server and authorization sign is all alright, but you make a request out server domain, you need a proxy CORS, if you and make request like to

axios.get(${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json) .then(res => { console.log(res) })
Soleil
  • 381
  • 4
  • 9
0

I tried navigating to azure portal, Opened my registered application, settings and under platform features/cors, I removed all urls and added *. This added authorization header for me. Adding * for cors is not recommended, but to test application on my localhost I tried this option. Once application is deployed, I removed * from cors allowed sites list and added my real site url there.

I came to this conclusion by using fiddler and postman side by side.

Kurkula
  • 6,386
  • 27
  • 127
  • 202