我在使用 Angular 创建 Web 应用程序时遇到问题,该应用程序访问由 Laravel 构建的 RESTful API。 虽然我创建了传递正确 header 的中间件,但它不起作用。
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $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');
}
}
谁能帮帮我?
最佳答案
嗯,我知道这是一个烦人的问题,但有两种解决方案。
1.
您为每个 API 调用路由定义 OPTIONS 方法,并使其传递您创建的中间件,如下所示:
Route::options('todos/{any?}', ['middleware' => 'cors', function(){return;}]);
Route::options('projects/{any?}', ['middleware' => 'cors', function(){return;}]);
2
您破解了 Laravel 核心类文件,以便它为每个 OPTIONS 请求传递 CORS header 。
在
/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 header
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),
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization',
]);
}))->bind($request);
}
$this->methodNotAllowed($methods);
}
所以对我来说,这两种解决方案都可以正常工作。选择是你的。 但是解决方案 #2 是对 Laravel 核心的一些 hack,如果你升级 Laravel 本身,你可能会遇到一些问题?但至少它的编码量更少。 :D
希望这些解决方案对您有所帮助。
关于angularjs - Angular + Laravel 项目的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41306481/