在本机浏览器提取中设置授权 [英] Setting authorization in native browser fetch
问题描述
我遇到一个问题,我似乎无法设置获取请求的标头,我想我错过了一些东西
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.
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
我遇到了同样的问题,并在今晚进行了一些调查。问题是跨域资源共享/ 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.
除非原点都是a nd destination与跨域请求相同,仅当请求到达支持CORS(跨源资源共享)的目标时才支持这些请求。如果没有,则不会通过。您通常会看到类似的错误。请求的资源上没有Access-Control-Allow-Origin标头
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
FORBIDDEN HEADER NAMES:
FORBIDDEN HEADER NAMES:
- https://developer.mozilla.org/en-US/docs/Glossary/Forbidden_header_name
- https://fetch.spec.whatwg.org/#forbidden-header-name
- 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/#thethe -open() - 方法
- https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
- http://arunranga.com/examples/access-control/credentialedRequest.html
- 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
最后,您选择前进的是:
1. JSONP
2.写不在浏览器中的代理
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
这篇关于在本机浏览器提取中设置授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!