错误 来自来源“http://localhost:3000”的“http://localhost:8000/sanctum/csrf-cookie”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头
nuxt axios 配置
import axios from "axios"
export default defineNuxtPlugin((NuxtApp) => {
axios.defaults.withCredentials = true;
axios.defaults.withXSRFToken = true;
axios.defaults.baseURL = 'http://localhost:8000'
return {
provide: {
axios: axios
},
}
})
*Laravel Cors*
'paths' => [
'api/*',
'/login',
'/register',
'/logout',
'/sanctum/csrf-cookie'
],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
翻译器此类设置不起作用,会出现上述错误
我尝试了代理,但没有任何效果(同样的错误)
const axios = require('axios');
module.exports = async function (req, res) {
const { data, headers } = await axios({
baseURL: 'http://localhost:8000',
url: req.url,
method: req.method,
headers: {
...req.headers,
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Headers': 'Content-Type',
},
data: req.body || null,
});
Object.keys(headers).forEach((key) => {
res.setHeader(key, headers[key]);
});
res.end(JSON.stringify(data));
};
nuxt.config.ts
serverMiddleware: [
{
path: '/api',
handler: '~/server-middleware/api-proxy.js',
},
],
解决方案
为 Laravel 安装 CORS 包:
composer require fruitcake/laravel-cors
或
composer require barryvdh/laravel-cors
将 Cors 中间件添加到 app/Http/Kernel.php 文件中的全局中间件堆栈中:
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
or
\Barryvdh\Cors\HandleCors::class,
];
发布你的 Cors 配置文件:
php artisan vendor:publish --tag="cors
”
之后,在 config/cors.php 文件中,配置应用程序允许的源:
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:3000'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
这就是全部