预检OPTIONS请求在浏览器中返回403 /禁止和不同的标题

时间:2018-04-24 08:42:18

标签: javascript google-chrome xmlhttprequest postman

我目前正在开发一个混合应用程序,它也可以在以后通过官方公司域在常规Web浏览器中运行。后端提供RESTful API,它支持所有类型的东西:获取条目,获取用户等。请求的来源至少是测试和应用程序,而不是域本身而是localhost。

现在导致问题的原因是使用POSTContent-Type: application/json和JSON正文发布。在浏览器中运行以进行测试时,Chrome会执行预检OPTIONS请求。我理解为什么,没有问题。不幸的是,请求的状态总是为403 - 我认为这与HTTP状态不对应,但更多的是基于响应本身对chrome的解释。 Chrome还表示缺少Access-Control-Allow-Origin标头。以下是我可以评估的一些事实:

  • chrome中的响应确实不包含此标题和其他标题。这完全没有意义,因为:
  • 相同的OPTIONS请求适用于Postman(HTTP 200)
  • Chrome的行为至少与Firefox相同
  • 我从Postman得到的回复包含所有必要的标题:

从OPTIONS请求返回的Postman-header:

Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Auth-Token, Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods: POST, PATCH, GET, PUT, OPTIONS, DELETE

有人可以帮助解决浏览器中的预检请求失败的原因吗?为什么OPTIONS响应在浏览器和Postman中不包含相同的标题?如果您需要更多信息,请告诉我们!我没有包含代码,因为OPTIONS请求是由浏览器启动的,而不是我。

非常感谢您提前和最好的问候。

编辑:以下是Chrome和邮差的完整请求:

铬:

General:
Request URL: [HIDDEN]/api2/entries/57734/comments
Request Method: OPTIONS
Status Code: 403 
Remote Address: [HIDDEN]
Referrer Policy: no-referrer-when-downgrade

Response:
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 20
Date: Tue, 24 Apr 2018 09:18:58 GMT
Expires: 0
Pragma: no-cache
Server: nginx/1.8.0
X-Application-Context: application:production
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Request:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-DE;q=0.8,en;q=0.7,en-US;q=0.6
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: [HIDDEN]
Origin: http://localhost:3000
Pragma: no-cache
User-Agent: Mozilla/5.0 (Linux; Android 8.0; Pixel 2 Build/OPD3.170816.012) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Mobile Safari/537.36

邮递员标题:

Access-Control-Allow-Headers: X-Auth-Token, Origin, X-Requested-With, Content-Type, Accept, Authorization
Access-Control-Allow-Methods: POST, PATCH, GET, PUT, OPTIONS, DELETE
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: X-Auth-Token
Access-Control-Max-Age: 1209600
Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Tue, 24 Apr 2018 09:24:04 GMT
Expires: 0
Pragma: no-cache
Server: nginx/1.8.0
Strict-Transport-Security: max-age=31536000
X-Application-Context: application:production
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

0 个答案:

没有答案