Angular + Laravel项目的CORS问题

时间:2016-12-23 18:47:43

标签: angularjs laravel cors

我无法使用Angular创建Web应用程序,Angular正在访问由Laravel构建的RESTful API。 虽然我已经创建了传递正确标头的中间件,但它不起作用。

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 个答案:

答案 0 :(得分:5)

嗯,这是一个令人烦恼的问题,我知道,但有2个解决方案。

1

为每个API调用路由定义OPTIONS方法,并使其通过您创建的中间件,如下所示:

Route::options('todos/{any?}', ['middleware' => 'cors', function(){return;}]);
Route::options('projects/{any?}', ['middleware' => 'cors', 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, 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

希望这些解决方案有所帮助。