【问题标题】:Laravel 8 from origin 'http://localhost:8000' has been blocked by CORS policy来自“http://localhost:8000”的 Laravel 8 已被 CORS 策略阻止
【发布时间】:2021-11-19 21:52:46
【问题描述】:

我在 Axios Laravel crossite 中遇到问题,它返回此错误:

CORS 策略已阻止从源“http://localhost:8000”访问“http://localhost/moddle/moodle/login/index.php”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经像 laravel-cors 一样关注并在 stackoverflow 上进行了回答,但都没有奏效。

这是我的 Axios:

let axiosConfig = {
                    headers: {
                        "Access-Control-Allow-Origin": "*",
                        'Content-Type': 'application/json;',
                        "Content-Type": "application/x-www-form-urlencoded",
                    }
                };
                axios.post('http://localhost/moddle/moodle/login/index.php', response.data, {
                    crossOrigin: null,
                }, axiosConfig).then(
                    response => {
                        console.log(true);
                        window.location.href = "http://localhost/moddle/moodle/my/";
                    }).catch(erorr => {

                });

在我的 cors.php 中

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

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

在我的中间件中

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,
        // 
        // \App\Http\Middleware\Cors::class,
    ];

【问题讨论】:

  • 感谢@KazikM提出更好的问题

标签: laravel


【解决方案1】:

请执行以下操作来解决问题。

php 工匠配置:缓存

【讨论】:

    【解决方案2】:

    您可以添加到 TrustHosts.php 中间件而无需做任何额外的事情。在此处阅读完整的解决方案:https://stackoverflow.com/a/70361284/2612926

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 2019-12-29
      • 2019-10-05
      • 2019-08-04
      • 2021-01-23
      • 2021-01-24
      • 2019-12-14
      • 2020-01-26
      相关资源
      最近更新 更多