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?
credentialsproperty though.credentials: 'include'instead. Unless your frontend JavaScript is also running from the originhttp://192.168.1.132:8000, your code’s making a cross-origin request. But withcredentials: 'same-origin'you’ve told the browser to only include credentials in same-origin requests, no cross-origin ones. The Authorization header (for HTTP authentication) is a type of credential fetch.spec.whatwg.org/#credentials, so the browser omits it unless (by usingcredentials: 'include'), you explicitly indicate you always want credentials included — even for cross-origin requestshttp://192.168.1.132:8000/testendpoint allows unauthenticated OPTIONS requests — that is, without the Authorization header. Because including the Authorization header triggers your browser to automatically on its own first send a CORS preflight OPTIONS request developer.mozilla.org/en-US/docs/Web/HTTP/… but the browser always omits all credentials from that OPTIONS request. So if thathttp://192.168.1.132:8000/testendpoint requires the Authorization header in OPTIONS requests too, the preflight will fail.192.168.1.132server doesn’t make the request same-origin. It would only be same-origin if the port number of the server for your frontend code is the same as the port number of the server you’re sending the request to. So unless your frontend code is also running from the server on port 8000, then the request your code is making is a cross-origin request.