我正在尝试将客户端请求从 Nuxt 3 发送到 api 路由,该路由通向 Laravel 中的身份验证控制器,但它返回:
Access to fetch at 'http://127.0.0.1:8000/api/authenticate' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
请求由 Nuxt 3 的 $fetch api 发送:
$fetch('http://127.0.0.1:8000/api/authenticate', {
method: 'POST',
body: form
}).then((res) => {console.log(res)})
请求似乎在到达控制器之前就被停止了。这是routes/api.php:
// works
Route::get('/test', function () {
return 'hello laravel';
});
// doesn't work, throws CORS error before request can reach Controller
Route::post('/authenticate', [AuthenticatedSessionController::class, 'test']);
// works
Route::post('/authenticate', function () {
return 'works';
});
从 Laravel 9.2 开始,似乎有一个 config/cors.php 文件可以配置,但我不知道如何配置。默认情况如下所示:
['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];
知道如何允许来自 Nuxt 3 的 api 请求 到 auth 路由 吗?
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号