CORS 预检请求错误:预检请求不允许重定向

Čam*_*amo 3 cors laravel axios

我有Vue3 应用程序,并根据 发送此标头的包的文档设置了 Access-Control-Allow-Origin 标头。每个常见的 GET 请求都有此标头,但如果表单请求发送 POST 请求,则响应中不包含 Access-Control-Allow-Origin 标头。它抛出一个错误

从源“https://vue.tatrytec.eu”访问“https://tatrytec.eu/api/article/store/”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制check:预检请求不允许重定向。

这是我的 config/cors.php

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];
Run Code Online (Sandbox Code Playgroud)

这是在 Kernel.php 中

protected $middleware = [
    // \App\Http\Middleware\TrustHosts::class,
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
Run Code Online (Sandbox Code Playgroud)

以下是抛出错误的 ArticlesController::store() 方法的代码:https://github.com/camohub/tatrytec.eu/blob/master/app/Http/Controllers/Api/ArticlesController.php#L63

有人可以告诉我应该在服务器代码中设置什么来发送所需的标头吗?多谢。

Čam*_*amo 18

此 CORS 问题是由预检请求重定向引起的,该重定向是由请求 URL 末尾的尾随斜杠引起的。看来服务器应用程序尝试重定向到不带尾部斜杠的规范网址。非常感谢作者对这个问题的回答

  • 惊人的。这节省了我更多的时间。 (4认同)
  • 额外的正斜杠“/”是主要问题,尤其是在查询字符串上。例如,使用“users?s=johndoe”代替“users/?s=johndoe”。 (3认同)
  • 可以还是不可以? (3认同)
  • 经过 5 个小时的调试后救了我 (2认同)