我正在尝试将客户端请求从 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 文件可以配置,但我不知道如何配置。默认情况如下所示:
<?php
return [
'paths' => ['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-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
对于 Laravel 开发者来说,开始 SSR Nuxt 之旅可能非常容易,尤其是当您使用 Homestead 编写 Laravel 时
您的 SSR Nuxt 站点可能使用
example.com作为域,您的 Laravel API 也可以通过前缀http://example.com/api调用(路由位于routes/api.php)Nginx 配置可能是
# before (Laravel default) location / { try_files $uri $uri/ /index.php?$query_string; } # after proxy_set_header X-Forwarded-For $remote_addr; location ~* ^/(api|broadcasting|storage)/ { try_files $uri $uri/ /index.php?$query_string; } location / { # the requests will be proxied to SSR Nuxt proxy_pass http://127.0.0.1:3000; }在你的 SSR Nuxt3 中
$fetch('/api/authenticate', { method: 'POST', body: form }).then((res) => {console.log(res)})之后,您就可以节省处理 CORS 的时间。
有关
proxy_set_header X-Forwarded-For $remote_addr; 的更多信息:在SSR Nuxt中,一些请求是从前端服务器发送的,一些请求是从客户端浏览器发送的。当来自前端服务器时,它可能会用自己的IP而不是客户端的IP来触发Laravel节流,为了避免这种情况,你可以添加一个
proxy_set_header X-Forwarded-For $remote_addr;代码> 首先。然后为您的 Nuxt 请求添加请求标头。在SSR Nuxt2(使用@nuxtjs/axios)中,plugins/axios.js
export default ({ $axios, store, req, error:nuxtError }) => { if (process.server) { $axios.setHeader('X-Forwarded-For', req.headers['x-forwarded-for']); } }在SSR Nuxt3中,由于包含官方HTTP客户端,因此不需要axios,请查看解决方案在这里