如何解决 Laravel + Nuxt.js 中的 CORS 错误

How to solve the CORS error in Laravel + Nuxt.js

我正在安装由 Nuxt.js(前端)和 Laravel(后端)在本地创建的旧项目。

Access to XMLHttpRequest at 'http://localhost:8000/api/user' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

这是我在 运行 项目中遇到的问题。

请求的前端配置(nuxt nuxt.config.js)。

user: {
    url: '/api/user',
    method: 'get',
    propertyName: false,
    withCredentials: true,
    headers: {
        X-Requested-With': 'XMLHttpRequest',
        Content-Type': 'application/json'
    }
}

后端配置(Laravel config/cors.php

'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,

我试图通过谷歌搜索找到解决方案,但没有找到正确的解决方案。

withCredetials is true

所以,我希望有人能在这方面帮助我。

在您的 laravel 应用中尝试这种方式:

php artisan serve --host YOUR_LOCAL_IP

YOUR_LOCAL_IP 是您的 ip,可以使用 linux 中的 ifconfig 命令和 windows 中的 ipconfig 命令访问。

最后你应该请求YOUR_LOCAL_IP:PORT/api