【发布时间】:2018-02-21 07:57:40
【问题描述】:
我正在尝试在 fetch 调用中发送自定义标头,但似乎由于某种原因没有发送标头。我发现一些问题似乎表明需要将 'cors' 模式设置为 fetch 选项,但我试过了,但没有任何作用。
在控制台中我收到此错误:
Fetch API cannot load http://localhost:8000/GroupRoutePermission. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8082' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
但是,如果我从我的 fetch 请求中删除 x-api-key 标头,我不会收到任何 CORS 控制台错误并且得到 JSON 响应就好了——我的 JSON 错误提示未设置 api 密钥(如预期)。
我还使用设置了 x-api-key 的 Postman 访问了我的端点,它工作正常。奇怪的是,我已经从我以前的项目中删除了以下代码,并且在该项目中,自定义标头发送得很好(即使没有 cors 模式),所以我不知道还能尝试什么。
let apiKey = ""
if (typeof localStorage.apiKey != 'undefined')
apiKey = localStorage.apiKey
else
window.location = "/login"
console.log(apiKey)
fetch(url,{
credentials: 'include',
mode: 'cors',
headers: new Headers({
'Content-Type': 'text/plain',
'x-api-key': localStorage.apiKey
})
})
Chrome 网络标签请求标头:
Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8,fr-CA;q=0.6,fr;q=0.4,en-CA;q=0.2
Access-Control-Request-Headers:x-api-key
Access-Control-Request-Method:GET
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8000
Origin:http://localhost:8082
Referer:http://localhost:8082/lists/ResearchTrial
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.90 Safari/537.36
发送带有 X-Api-Key 的响应标头:
HTTP/1.1 200 OK
Host: localhost:8000
Connection: close
X-Powered-By: PHP/5.5.38-4+deb.sury.org~xenial+1
Allow: GET,HEAD
Cache-Control: no-cache
Content-Type: text/html; charset=UTF-8
Date: Tue, 12 Sep 2017 19:30:58 GMT
如果我在请求中删除 X-Api-Key 的响应标头:
HTTP/1.1 200 OK
Host: localhost:8000
Connection: close
X-Powered-By: PHP/5.5.38-4+deb.sury.org~xenial+1
Access-Control-Allow-Origin: http://localhost:8082
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Content-Length, Accept- Encoding, X-Api-Key
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
Cache-Control: no-cache
Content-Type: application/json
Date: Tue, 12 Sep 2017 19:28:29 GMT
请帮忙!
【问题讨论】:
-
确实是重复的!感谢您链接到该问题/答案!
标签: javascript cors fetch-api