I'm coming across an issue where I can't seem to set the headers for a fetch request and I think I'm missing something
var init = {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer myKey'
}
};
return fetch(url, init).then(function(response){...
When the request is inspected in the network tab, I'm not seeing the headers get set and instead see
Access-Control-Request-Headers:accept, authorization, content-type
when I would expect to see
Authorization: Bearer myKey
Content-Type: application/json
Accept: application/json
I've also tried using the native Headers() with zero difference.
Am I missing something here?
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.
The fetch() method in JavaScript is used to request to the server and load the information on the webpages. The request can be of any APIs that return the data of the format JSON or XML. This method returns a promise.
Fetch defaults to GET requests, but you can use all other types of requests, change the headers, and send data. Let's create a POST request. The method key will have the value 'POST' . body will be set equal to the JSON.
I was having the same issue and took a bit of investigating this evening. The problem is cross-origin resource sharing / CORS. With Fetch it is the default and it makes things considerably more complex.
Unless Both the origin and destination are the same it is a cross-domain request, and these are only supported if the request is to a destination that supports CORS ( Cross-Origin Resource Sharing ). If it does not then it will not go through. You'll usually see an error like No 'Access-Control-Allow-Origin' header is present on the requested resource
This is why you can not do Authorization headers on non-CORS sites; see #5 and basic headers
FORBIDDEN HEADER NAMES:
And unfortunately, before you try the XMLHttpRequest route, the same applies: This is the same with XMLHttpRequest:
Finally, your choices to move forward are: 1. JSONP 2. Write a proxy that is not in the browser 3. Put CORS on the destination server
This article sums it up nicely
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