Angular + Laravel 项目的 CORS 问题 [英] CORS issue for Angular + Laravel project
问题描述
我在使用 Angular 创建 Web 应用程序时遇到问题,Angular 正在访问 Laravel 构建的 RESTful API.虽然我创建了传递正确标头的中间件,但它不起作用.
I am having trouble to create web app using Angular which is accessing to RESTful API built by Laravel. Although I have created middleware which passes correct headers, it does not work.
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');
}
}
有人可以帮我吗?
推荐答案
嗯,这是一个很烦人的问题,我知道,但是有 2 个解决方案.
Well, this is a kind of annoying issue, I know, but there are 2 solutions.
您为每个 API 调用路由定义 OPTIONS 方法,并使其通过您创建的中间件,如下所示:
You define OPTIONS method for every API calling route, and make it pass the middleware you created like following:
Route::options('todos/{any?}', ['middleware' => 'cors', function(){return;}]);
Route::options('projects/{any?}', ['middleware' => 'cors', function(){return;}]);
2
您破解 Laravel 核心类文件,以便它为每个 OPTIONS 请求传递 CORS 标头.
2
You hack Laravel core class file, so that it passes CORS header for every OPTIONS request.
在
/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 标头
Update this function to following, so that it will pass CORS headers for OPTIONS request
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 核心的一些破解,如果您升级 Laravel 本身可能会遇到一些问题?但至少它的编码更少.:D
So for me, both solutions work okay. Choice is yours. But solution #2 is something hack on Laravel core, you might have some issues if you upgrade Laravel itself? But at least it has less coding. :D
希望这些解决方案会有所帮助.
Hope these solutions will be helpful.
这篇关于Angular + Laravel 项目的 CORS 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!