我正在尝试在fetch呼叫中发送自定义标头,但是似乎由于某种原因没有发送标头。我发现一些问题似乎表明需要将" CORS"模式设置为提取选项,但我尝试过,但没有改变。
在控制台中,我会遇到此错误:
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.
但是,如果我从我的提取请求中删除X-API-KEY标题,我不会遇到任何CORS控制台错误,并且可以得到JSON响应 - 我的JSON带有错误,说API键未设置(如预期)。
我还使用X-Api-Key Set的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
请帮助!
我已经从我以前的一个项目中删除了以下代码,并且在该项目中,自定义标头的发送得很好(即使没有CORS模式),所以我对其他尝试的方法感到茫然。
该项目也提出了跨域请求吗?
我的猜测是,API会在Auth失败时发送CORS标头,但在Auth成功时不会发送标头。这不会影响邮递员,这不必担心CORS。
您应该能够通过发送身份验证的请求并检查响应标头来在Postman中确认这一点。