Setting authorization in native browser fetch

2020-07-09 03:41发布

问题:

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?

回答1:

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

  • https://fetch.spec.whatwg.org/#concept-headers-guard
  • https://fetch.spec.whatwg.org/#simple-header

FORBIDDEN HEADER NAMES:

  • https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
  • https://fetch.spec.whatwg.org/#forbidden-header-name

And unfortunately, before you try the XMLHttpRequest route, the same applies: This is the same with XMLHttpRequest:

  • https://www.w3.org/TR/XMLHttpRequest/#the-open()-method
  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  • http://arunranga.com/examples/access-control/credentialedRequest.html

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