Loading

再谈options

场景

部署服务过程中遇到了跨域问题,仅仅添加了跨域字段 Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Allow-Headers 还不行。

Access-Control-Allow-Credentials true;
Access-Control-Allow-Origin *;
Access-Control-Allow-Headers 'Content-Type,Authorization';
Access-Control-Allow-Methods 'GET,POST,PUT,DELETE,OPTIONS';
Access-Control-Max-Age 3600;

原因1,预检的响应不正确

预检请求和对应的响应示例:
当请求header中有 header1,而allow-headers 中没有这个header1时,浏览器将会阻止这个请求。

OPTIONS /doc HTTP/1.1
Host: bar.other
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Connection: keep-alive
Origin: https://foo.example
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-PINGOTHER, Content-Type

HTTP/1.1 204 No Content
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2
Access-Control-Allow-Origin: https://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
Vary: Accept-Encoding, Origin
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive

原因2: Access-Control-Allow-Headers 不包含 header中字段

比如:你的请求中有 X-PINGOTHER 的hader,而Access-Control-Allow-Headers 头中不含这个 X-PINGOTHER 则会被浏览器阻止

其他原因:浏览器console里都写的比较清楚,使用搜索引擎即可解决

参考:https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS

posted @ 2024-09-09 12:37  ZJH_BLOGS  阅读(10)  评论(0编辑  收藏  举报