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?
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.
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.
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", });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With