thinkphp 设置跨域请求

XMLHttpRequest cannot load http://localhost/mz/goods/getList. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8020' is therefore not allowed access.

解决方案:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

为ajaxReturn 方法设置允许跨域访问的请求头。

thinkphp 设置跨域请求_第1张图片

参考地址:http://blog.sina.com.cn/s/blog_6751f30b0102w2x1.html,http://stackoverflow.com/questions/20433655/no-access-control-allow-origin-header-is-present-on-the-requested-resource-or

 

 

thinkphp 5版本解决

情景:

     uni-app使用vue框架开发混合APP,虽然APP或者小程序没有跨域,但希望就是写完这个既有H5,又有APP,小程序等,所以能通过后端解决跨域最好。但是不知道是vue的原因还是什么,在PHP接口基类中添加了header头完全不起作用。官方给出的方法也有,具体可以看https://uniapp.dcloud.io/api/request/request。

    

分析:

 1. 以前的做法是在接口添加以下部分就可以解决ajax的跨域(虽然也用过jsonp)。

// 指定允许其他域名访问  
        // header('Access-Control-Allow-Origin:*');
        // // 响应类型 // header('Access-Control-Allow-Methods:*'); // // 响应头设置 // header('Access-Control-Allow-Headers:*');

 

2.  添加后请求,报错“Access to XMLHttpRequest at 'http://www.unxxx.com/api/v1.user/login' from origin 'http://192.168.2.121:8000' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.”;自定义的请求头token不被允许。因为接口请求需要带上token,把token放在自定义请求头上再传到PHP。

 

3. 于是就将token改为普通参数方式传递,但依然报错,Access to XMLHttpRequest at 'http://www.xxxxxx.com/api/v1.user/login' from origin 'http://192.168.2.121:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource。

thinkphp 设置跨域请求_第2张图片

 

4. 以上可以看出就是普通跨域报错了,然后看一下浏览器的请求响应报文。

thinkphp 设置跨域请求_第3张图片

 

5. 发现返回过来的头部信息完全不是自己在接口上指定的,抱着试一试的念头,把跨域请求放到了TP5.1的入口文件\public\index.php,竟然就可以正常请求了,目前我也不清楚原因是什么。

thinkphp 设置跨域请求_第4张图片

 

 

 

 

转载于:https://www.cnblogs.com/jasonLiu2018/p/10939304.html

你可能感兴趣的:(php,javascript,后端)