跨域(跨源)问题解决

Chrome报错内容:

Access to XMLHttpRequest at 'http://xxxx' from origin 'http://localhost:3000' 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://localhost:9001/educenter/member/register', but only one is allowed.

Firefox报错内容:

已拦截跨源请求:同源策略禁止读取位于 http:**** 的远程资源。(原因:CORS 头缺少 'Access-Control-A...

解决办法

解决办法一:

var url='http://localhost:9001/educenter/member/register"
       +"?id=1&callback=?';
   $.ajax({
     url:url,
     dataType:'jsonp',
     processData: false, 
     type:'get',
     success:function(data){
       alert(data.name);
     },
     error:function(XMLHttpRequest, textStatus, errorThrown) {
       alert(XMLHttpRequest.status);
       alert(XMLHttpRequest.readyState);
       alert(textStatus);
     }});

解决办法二:

var url="http://localhost:9001/educenter/member/register"
    +"?id=1&callback=?";
$.jsonp({
  "url": url,
  "success": function(data) {
    $("#current-group").text("当前工作组:"+data.result.name);
  },
  "error": function(d,msg) {
    alert("Could not find user "+msg);
  }
});

解决办法三:

被请求页面加上下面代码,最好content填写域名
<meta http-equiv="Access-Control-Allow-Origin" content="*">

解决办法四:

header(“Access-Control-Allow-Origin: *”);

解决办法五:

修改nginx配置文件

server {
        listen       81;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
			#####自定义模块,解决跨域问题,*表示匹配所有,生产不推荐
			add_header 'Access-Control-Allow-Origin' '*';
			add_header 'Access-Control-Allow-Credentials' 'true';
			add_header 'Access-Control-Allow-Methods' 'GET,POST';
			add_header 'Access-Control-Allow-Headers' 'x-requested-with,content-type';
			#####自定义模块,解决跨域问题,*表示匹配所有,生产不推荐
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

解决办法六:

如果是Springboot项目,在Controller上添加跨域注解 @CrossOrign

报错原因:

协议 、 域名 、端口有一个不一致,就会存在跨域问题,CORS一般不需要在浏览器配置,浏览器发现这次跨源AJAX请求是简单请求,就自动在头信息之中,添加一个Origin字段,Origin字段用来说明,本次请求来自哪个源(协议 、 域名 、端口)。服务器根据这个值,决定是否同意这次请求,也就是说服务器会存在一份白名单,说明哪一些源是可以被允许的,而Access-Control-Allow-Origin就是包含在回应头里的白名单。浏览器发现,这个回应的头信息没有包含Access-Control-Allow-Origin字段,就知道出错了,从而抛出一个错误,也就是遇到的提示,是返回结果被浏览器拦截了,而不是请求发不出。

所以你需要的是在服务器上配置这个白名单,而不是更改页面

posted @ 2020-11-24 11:30  等不到的口琴  阅读(1051)  评论(0编辑  收藏  举报