Fetch不会发送自定义标头

时间:2017-09-12 18:44:42

标签: javascript cors fetch-api

我正在尝试在提取调用中发送自定义标头,但似乎由于某种原因没有发送标头。我发现一些问题似乎表明“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模式),所以我不知道还有什么可以尝试。< / p>

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

请帮忙!

1 个答案:

答案 0 :(得分:0)

  

我已经将以下代码从我之前的项目中删除了,在该项目中,自定义标头发送得很好(即使没有cors模式),所以我不知道还有什么可以尝试。

该项目是否也在提出跨域请求?

我的猜测是,当auth失败时,API将发送cors标头,但在auth成功时不会发送标头。这不会影响Postman,后者不必担心角色。

您应该能够通过发送经过身份验证的请求并检查响应标头在Postman中进行确认。