来自“http://localhost:8000”的 Laravel 8 已被 CORS 策略阻止

Posted

技术标签:

【中文标题】来自“http://localhost:8000”的 Laravel 8 已被 CORS 策略阻止【英文标题】:Laravel 8 from origin 'http://localhost:8000' has been blocked by CORS policy 【发布时间】: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 一样关注并在 *** 上进行了回答,但都没有奏效。

这是我的 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提出更好的问题 【参考方案1】:

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

php 工匠配置:缓存

【讨论】:

【参考方案2】:

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

【讨论】:

以上是关于来自“http://localhost:8000”的 Laravel 8 已被 CORS 策略阻止的主要内容,如果未能解决你的问题,请参考以下文章

React 代理错误:无法将请求 /api/ 从 localhost:3000 代理到 http://localhost:8000 (ECONNREFUSED)

来自 django 基本模板文件中 url 的变量

使用 Laravel/ajax 获取 http://localhost:8000/= 404(未找到)

POST http://localhost:8000/offers-ajax/store 419 (未知状态) Laravel AJAX

POST http://localhost:8000/api/projects/ 500(内部服务器错误)

删除 http://localhost:8000/product/[object%20Object] 500(内部服务器错误)