跨境派

跨境派

跨境派,专注跨境行业新闻资讯、跨境电商知识分享!

当前位置:首页 > 卖家故事 > 前后端分离常见跨域问题及解决方法

前后端分离常见跨域问题及解决方法

时间:2024-04-09 16:40:25 来源:网络cs 作者:亙句 栏目:卖家故事 阅读:

标签: 解决  方法  分离 
阅读本书更多章节>>>>

1、has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

原因:跨域的allow_headers没有设置authorization

 "allow_headers": ["Referer", "Accept", "Origin", "User-Agent"]

解决方法,加个Authorization就可以

"allow_headers": ["Referer", "Accept", "Origin", "User-Agent", "Authorization"]

2、has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The value of the ‘Access-Control-Allow-Credentials’ header in the response is ‘’ which must be ‘true’ when the request’s credentials mode is ‘include’. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

原因:Access-Control-Allow-Credentials设置为True, Control-Allow-Origin就不能为"*"。

解决方法
(1)前端配置withCredentials=true, 后端把Origin设置为指定源,同时加上Credentials=true

http {    server {        listen 80;        server_name localhost;        修改为        add_header 'Access-Control-Allow-Origin' 'host:port';        add_header "Access-Control-Allow-Credentials" "true"; # 新增这一个        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';    }

(2) 前端配置withCredentials=false, 后端把Origin不修改

3、出现多个origin, has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: The ‘Access-Control-Allow-Origin’ header contains multiple values ‘http://192.168.3.46:9528, *’, but only one is allowed.

原因:可能是出现重复配置跨域导致。我出现这个原因因为nginx和flask两个都配置了跨域请求,导致一个出现这种情况
下面是我配置信息:

# falsk配置信息cors = CORS(resources={    r"*": {        "origins": "*",        "methods": ["PUT", "GET", "POST", "DELETE", "OPTIONS"],        "allow_headers": ["Referer", "Accept", "Origin", "User-Agent", "Token"],    }})
# nginx配置信息http {    server {        listen 80;        server_name localhost;        add_header 'Access-Control-Allow-Origin' '*';        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';        add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';        location / {            proxy_pass http://flask_app:8000;            proxy_set_header Host $host;            proxy_set_header X-Real-IP $remote_addr;        }    }

解决方法:两个保留其中一个就可以

阅读本书更多章节>>>>

本文链接:https://www.kjpai.cn/gushi/2024-04-09/156114.html,文章来源:网络cs,作者:亙句,版权归作者所有,如需转载请注明来源和作者,否则将追究法律责任!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。

文章评论