怎么在ThinkPHP 5.1中配置跨域

今天就跟大家聊聊有关怎么在ThinkPHP 5.1中配置跨域,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

按照网上大部分关于跨域请求的配置,基本都是以下三行代码:

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

把这三行代码放到 /route/route.php,/route/api.php,/public/index.php 以及受访问的控制器文件头部均出现以下报错信息:

Failed to load http://url.com/main/info: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.Origin 'null' is therefore not allowed access.The response had HTTP status code 404.

说明配置并没有生效。

查阅 ThinkPHP 的文档,文档给出的例子:

Route::get('new/:id', 'News/read')
  ->ext('html')
  ->allowCrossDomain();

意思是只需要在路由的尾部添加 allowCrossDomain() 即可,所以我在每个需要进行跨域访问的路由后都添加了 ->allowCrossDomain(),问题得以解决。

另外的问题

由于前端的 AJAX 请求通常需要携带 token 验证,所以还需要将 token 添加到 Access-Control-Allow-Headers

文档的例子是

Route::get('new/:id', 'News/read')
  ->ext('html')
  ->header('Access-Control-Allow-Origin','thinkphp.cn')
  ->header('Access-Control-Allow-Credentials', 'true')
  ->allowCrossDomain();

我按照上面的方法添加了 ->header('Access-Control-Allow-Headers','token') ,再次请求出现了下面的报错:

Failed to load: http://url.com/main/info: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

thinkphp是什么

thinkphp属于一种免费的开发框架,能够用于开发前端网页,最早thinkphp是为了简化开发而产生的,thinkphp同时也是遵循Apache2协议,最初是从Struts演变过来,也把国外一些好的框架模式进行利用,使用面向对象的开发结构,兼容了很多标签库等模式,它能够更方便和快捷的开发和部署应用,当然不仅仅是企业级应用,任何php应用开发都可以从thinkphp的简单、兼容和快速的特性中受益。

看完上述内容,你们对怎么在ThinkPHP 5.1中配置跨域有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。