登录  /  注册
如何配置 Laravel CORS 接受 Nuxt 3 代理 HTTP 请求?
P粉739886290
P粉739886290 2023-12-24 19:42:58
[Vue.js讨论组]

我正在尝试将客户端请求从 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 路由 吗?

P粉739886290
P粉739886290

全部回复(1)
P粉917406009

对于 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,请查看解决方案在这里

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号