簡體   English   中英

Angular + Laravel項目的CORS問題

[英]CORS issue for Angular + Laravel project

我無法使用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');
    }
}

任何人都可以幫助我嗎?

嗯,這是一個令人討厭的問題,我知道,但有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

希望這些解決方案有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM