问题描述:
tp5 跨域问题
原因分析:
前后端分离,要在请求的header中加入自定义的一些字段,如此在请求过程中就回出现跨域的问题,返回信息中提示Access-Control-Allow-Headers中自定义的字段没有发现。但是按照tp5官方的文档已经设置了Access-Control-Allow-Headers,并且在route中加入了->allowCrossDomain()代码如下入口文件:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST,GET');
header('Access-Control-Allow-Credentials:true');
header("Access-Control-Allow-Headers:Accept,Referer,User-Agent,X-Requested-With,Content-Type,token");
route.php:
Route::group('admin',function(){
Route::post('index','api/admin/index');
})->allowCrossDomain();
结果还是返回跨域并且token字段不存在
解决方案:
明明已经将token放到了header中,问什么还是提示token字段不存在呢,有两个可能导致一是:设置的配置没有生效,二是:设置的配置被覆盖。之后在thinkphp/library/think/route/rule.php中发现checkCrossDomain方法将设置好的header覆盖了,于是将token填入header中跨域问题解决了
protected function checkCrossDomain($request)
{
if (!empty($this->option['cross_domain'])) {
$header = [
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,token',
];