如何在 Laravel 中使用 auth:api passport 中间件添加 CORS 中间件?

How to add CORS middleware with auth:api passport middleware in Laravel?

我已将 Laravel Passport 用于经过身份验证的端点。我面临这些 API 的 CORS 问题。

在app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

use Closure;

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-Methods', "PUT,POST,DELETE,GET,OPTIONS")
                ->header('Access-Control-Allow-Headers', "Accept,Authorization,Content-Type");
    }
}

在app/Http/Kernel.php中,在中间件数组中添加

\App\Http\Middleware\Cors::class,

在routes/api.php,

Route::post('auth/login', 'PassportController@login'); //working 
Route::middleware('auth:api')->group(function () {
Route::get('vehicle/all', 'VehicleController@getVehicles'); //not working: facing CORS error
});

我已经使用了auth:api(Laravel护照)进行授权。 auth:api 组中端点的 CORS 错误。 'auth/login' 等组外的端点工作正常。 如何处理 Route::middleware('auth:api') 组内的 cors 错误?

您需要指定允许的域,浏览器不再接受通配符“*”。

如果您有多个域调用您的 api,您可以使用 $_SERVER['HTTP_HOST']

使其动态化
<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $domain = $request->getHost();
        // or $domain =  $_SERVER['HTTP_HOST'];
        return $next($request)
            ->header('Access-Control-Allow-Origin', $domain)
                ->header('Access-Control-Allow-Methods', "PUT,POST,DELETE,GET,OPTIONS")
                ->header('Access-Control-Allow-Headers', "Accept,Authorization,Content-Type");
    }
}