vue.js 如何配置Laravel CORS接受Nuxt 3代理HTTP请求?

ecbunoof  于 2022-12-14  发布在  Vue.js
关注(0)|答案(1)|浏览(198)

我尝试从Nuxt 3api route发送一个客户端请求,这会导致laravel中的authentication controller,但它返回:

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)})

请求似乎在到达controller之前被停止。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,

];

你知道我怎么能允许api requests从nuxt3到auth routes吗?

xqkwcwgp

xqkwcwgp1#

对于laravel开发人员来说,开始SSRNuxt之旅可能非常容易,特别是当您使用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 Nuxt 3

$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 Nuxt 2中(带有@nuxtjs/axios),插件/axios.js

export default ({ $axios, store, req, error:nuxtError }) => {
    if (process.server) {
        $axios.setHeader('X-Forwarded-For', req.headers['x-forwarded-for']);
    }
}

在SSRNuxt 3中,由于包含一个官方HTTP客户端,因此您不需要axios,请在此处查看解决方案

相关问题