Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authorization header not working in fetch - React Native

I am making a request to an API that I have on my computer (192.168.1.132) with react native from my phone (in the same network):

fetch('http://192.168.1.132:8000/test', {
  method: 'GET',
  headers: { 'Authorization': 'Bearer 4uFPmkP5326DXcRuHDKjRRrmhdeIBJ'},
  credentials: 'same-origin'
  })
  .then((response) => response.json())
  .then((responseJson) => {
    console.log('RESPONSE: ' + JSON.stringify(responseJson))
  })

But I am sniffing the request and it has not the Authorization header (any other that I put will appear, but not Authorization). In Xcode I have enabled 'AllowArbitraryLoads'. So my API returns 401 (Unauthorized) because obviously there is no Authorization header. Why is it not included in my request?

like image 508
epord Avatar asked Mar 17 '18 16:03

epord


People also ask

How do I pass authorization header in fetch request?

You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter.

How do I pass authorization bearer in header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

How do I send the authorization header in react JS?

To use an authorization header with fetch in React Native, we set the headers option when we call fetch . fetch(url, { method: "post", headers: new Headers({ Authorization: "Basic " + btoa("username:password"), "Content-Type": "application/x-www-form-urlencoded", }), body: "foo=1&bar=2", });


1 Answers

You need a trailing slash on your url for headers to attach. As pointed out in the comments, make credentials say 'include'. If your API attaches a CSRF token in the pre-flight, then it will include that cookie as well.

like image 92
Ryan Dines Avatar answered Nov 15 '22 08:11

Ryan Dines