Laravel VerifyCsrfToken 排除无效

Laravel VerifyCsrfToken exclude not working

我遇到一个问题,将 /api 路由从验证令牌中排除。

我正在尝试排除所有路由但不起作用

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        //
        '*',
    ];
}

我的建议是,创建一个中间件并在您的路由中使用它:

创建app/Http/Middleware/Cors.php

<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;

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

修改app/Http/Kernel.php

    protected $routeMiddleware = [
        ...
        'cors' => \App\Http\Middleware\Cors::class,
    ];

最后,在你的路由文件中使用它,例如:routes/web.php

Route::middleware(['cors'])->group(function () {
    Route::get('/', 'YourController@yourFunction');
});