angularjs – Angular Laravel项目的CORS问题
发布时间:2020-12-17 17:27:51 所属栏目:安全 来源:网络整理
导读:我无法使用Angular创建Web应用程序,Angular正在访问由Laravel构建的RESTful API. 虽然我已经创建了传递正确标头的中间件,但它不起作用. class Cors{ /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $ne
我无法使用Angular创建Web应用程序,Angular正在访问由Laravel构建的RESTful API.
虽然我已经创建了传递正确标头的中间件,但它不起作用. class Cors { /** * Handle an incoming request. * * @param IlluminateHttpRequest $request * @param Closure $next * @return mixed */ public function handle($request,Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin','*') ->header('Access-Control-Allow-Credentials','true') ->header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS') ->header('Access-Control-Allow-Headers','X-Requested-With,Content-Type,X-Auth-Token,Origin,Authorization'); } } 任何人都可以帮助我吗? 解决方法
嗯,这是一个令人讨厌的问题,我知道,但有2个解决方案.
1. 您为每个API调用路由定义OPTIONS方法,并使其通过您创建的中间件,如下所示: Route::options('todos/{any?}',['middleware' => 'cors',function(){return;}]); Route::options('projects/{any?}',function(){return;}]); 2 你破解Laravel核心类文件,以便它为每个OPTIONS请求传递CORS头. 在里面 /vendor/laravel/framework/src/framework/Illuminate/Routing/RouteCollection.php 你会发现以下功能 protected function getRouteForMethods($request,array $methods) { if ($request->method() == 'OPTIONS') { return (new Route('OPTIONS',$request->path(),function () use ($methods) { return new Response('',200,['Allow' => implode(',',$methods)]); }))->bind($request); } $this->methodNotAllowed($methods); } 将此函数更新为以下内容,以便它将为OPTIONS请求传递CORS标头 protected function getRouteForMethods($request,[ 'Allow' => implode(',$methods),'Access-Control-Allow-Origin' => '*','Access-Control-Allow-Credentials' => 'true','Access-Control-Allow-Methods' => 'GET,OPTIONS','Access-Control-Allow-Headers' => 'X-Requested-With,Authorization',]); }))->bind($request); } $this->methodNotAllowed($methods); } 所以对我来说,两种解决方案都可行.选择是你的. 希望这些解决方案有所帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |