发布时间:2021/12/08 作者:天马行空 阅读(3155)
今天和前端对接新写的后台接口,一上来就报了两个错误。
Access to XMLHttpRequest at 'http://xxx.com/user/login' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Access to XMLHttpRequest at 'http://xxx.com/user/logout' from origin 'http://localhost:8100' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
这是常见的跨域请求问题,在前后端分离的项目中常见,前端项目直接用接口域名请求,根据浏览器的网络请求规则,跨域是不允许这样直接调用的(会被当黑客恶意攻击给拦截掉),从而导致该跨域请求被拒绝。
解决方案:Thinkphp6.0 已经封装好了跨域请求的内置中间件: think\middleware\AllowCrossDomain,在 app\middleware.php 文件中,引入内置中间件即可。如果你在header中有添加自己的元素进去,那么就需要继承框架中的中间键,重写一下就好了。
不是thinkphp框架,直接通过设置header解决
header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, OPTIONS, DELETE'); header('Access-Control-Allow-Headers: *');