前端ajax请求跨域问题记录

在其他的网站上加载远程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环境修改域名配置:

    DocumentRoot "E:\PHP\www\tp\public"
    ServerName r.com
    ServerAlias 
  
      Options FollowSymLinks ExecCGI
      AllowOverride All
      Order allow,deny
      Allow from all
      Require all granted
      Header set Access-Control-Allow-Origin *  #添加这一行
  


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

你可能感兴趣的:(前端,PHP)