前端ajax请求跨域问题记录

16 篇文章 1 订阅

在其他的网站上加载远程js执行一些操作遇到跨域问题:

ccess to XMLHttpRequest at 'http://r.com/index.php/api/index/tpl' from origin 'http://991999.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET http://r.com/index.php/api/index/tpl net::ERR_FAILED

请求的接口是php服务器,在服务器后端代码添加:
header("Access-Control-Allow-Origin:*");

或者在apache环境修改域名配置:
<VirtualHost *:80>
    DocumentRoot "E:\PHP\www\tp\public"
    ServerName r.com
    ServerAlias 
  <Directory "E:\PHP\www\tp\public">
      Options FollowSymLinks ExecCGI
      AllowOverride All
      Order allow,deny
      Allow from all
      Require all granted
      Header set Access-Control-Allow-Origin *  #添加这一行
  </Directory>
</VirtualHost>

nginx环境:
location / {  
    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,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
    }
} 
遇到一点问题:
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods","GET,POST");
header("Access-Control-Allow-Credentials", "true");
这三行代码一起使用的时候会出错,跨域不了。
只用Origin即可

还可以使用ajax的jsonp。

 

 

jquery-1.8.2.min.js:2 Access to XMLHttpRequest at 'http://r.com/index.php/api/index/tpl' from origin 'http://991999.net' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

因为自己的多了withCredentials,注释掉即可:

$.ajax({
        type:'GET',
        url:url,
        async:false,
        dataType: 'html',
        // xhrFields: {
        //     withCredentials: true
        // },
        timeout: 10000,
        crossDomain: true,
        success:function(data){
            var div = document.createElement('div');
            div.innerHTML = data;
            div.id=id;
            document.body.appendChild(div);
        }
    });

 

更多:

https://segmentfault.com/a/1190000012550346

http://www.ruanyifeng.com/blog/2016/04/cors.html

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值