在本机浏览器获取中设置授权

2022-01-20 00:00:00 browser fetch javascript

我遇到了一个问题,我似乎无法为获取请求设置标头,并且我认为我遗漏了一些东西

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

什么时候能看到

Authorization: Bearer myKey
Content-Type: application/json
Accept: application/json

我也尝试过使用零差异的原生 Headers().

I've also tried using the native Headers() with zero difference.

我错过了什么吗?

推荐答案

今天晚上我遇到了同样的问题并进行了一些调查.问题是跨域资源共享/CORS.使用 Fetch 它是默认设置,它使事情变得更加复杂.

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.

除非来源和目的地相同,否则它是跨域请求,并且仅当请求到支持 CORS(跨域资源共享)的目的地时才支持这些请求.如果没有,那么它不会通过.您通常会看到类似 No 'Access-Control-Allow-Origin' header is present on the requested resource

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

这就是为什么你不能在非CORS网站上做授权标头;参见 #5 和基本标题

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

禁止的标题名称:

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

不幸的是,在您尝试 XMLHttpRequest 路由之前,同样适用:这与 XMLHttpRequest 相同:

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()-方法
  • https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
  • http://arunranga.com/examples/access-control/credentialedRequest.html

最后,您要继续前进的选择是:1.JSONP2.写一个不在浏览器中的代理3. 将CORS放在目的服务器上

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

这篇文章总结的很好

相关文章