带有水果蛋糕的 Laravel CORS

Qli*_*Qli 6 cors laravel reactjs laravel-middleware react-redux

我用laravel后端制作了反应项目......我有一个CORS问题,我像下面的链接一样做所有事情,用水果蛋糕。

API 的 Laravel 6 CORS 策略问题, 但仍然无法正常工作。

cors.php:

        'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
Run Code Online (Sandbox Code Playgroud)

而且,内核中间件是:

        protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

        \Fruitcake\Cors\HandleCors::class,
    ];
Run Code Online (Sandbox Code Playgroud)

还有什么问题?

gli*_*a93 8

以下是使用时的一些问题fruitcake/laravel-cors

  • HandleCors中间件放在$middlewarein的顶部app/Http/Kernel.php
protected $middleware = [
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
Run Code Online (Sandbox Code Playgroud)

将它放在底部或介于两者之间是行不通的,因为请求可能会被其他具有更高优先级的中间件拒绝。

  • 千万不要死或控制器退出。

例如,以下将不起作用:

Route::get('/cors-test', function() {
   dd("This won't work");
});
Run Code Online (Sandbox Code Playgroud)

因为Fruitcake\Cors\HandleCors::handle方法在处理请求添加了相关的标头:

Fruitcake\Cors\HandleCors.php

public function handle($request, Closure $next)
{
    // --- omitted

    // Handle the request
    $response = $next($request); // <--- if you die here

    if ($request->getMethod() === 'OPTIONS') {
        $this->cors->varyHeader($response, 'Access-Control-Request-Method');
    }
    
    // you will never reach here
    return $this->addHeaders($request, $response);
}
Run Code Online (Sandbox Code Playgroud)
  • 更改后清除配置缓存app/config/cors.php
$ php artisan config:cache
Run Code Online (Sandbox Code Playgroud)


小智 -1

php artisan config:clear
php artisan route:clear
php artisan cache:clear
Run Code Online (Sandbox Code Playgroud)

确保您的权限设置正确(例如存储可写)