thinkphp:允许接口跨域访问(thinkphp v6.0.12LTS)
一,php代码:
public function list() { ... 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'); $res = ["list"=>$arr, "per_page"=>10, "total"=>3, "current_page"=>$page, ]; return Result::Success($res); }
说明:刘宏缔的架构森林是一个专注架构的博客,
网站:https://blog.imgtouch.com
原文: https://blog.imgtouch.com/index.php/2023/06/04/thinkphp-yun-xu-jie-kou-kua-yu-fang-wen-thinkphp-v6-12lts/
对应的源码可以访问这里获取: https://github.com/liuhongdi/
或: https://gitee.com/liuhongdi
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,查看效果
未允许跨域前的响应头:
说明:此时如果通过h5端用js直接访问接口,会报错如下:
Access to XMLHttpRequest at 'http://api.lhdtest.com/item/list?page=1' from origin 'http://localhost:8080'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
允许跨域后的响应头:
说明:此时可以通过h5端用js直接访问接口,不会报跨域错误
三,查看thinkphp的版本:
[lhdop@blog tpapibase]$ php think version v6.0.12LTS