How to configure Laravel CORS to accept Nuxt 3 proxy HTTP requests?
P粉739886290
P粉739886290 2023-12-24 19:42:58
0
1
580

I'm trying to send a client request from Nuxt 3 to the api route that leads to the authentication controller in Laravel, but it return:

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.

Requests are sent by Nuxt 3’s $fetch api:

$fetch('http://127.0.0.1:8000/api/authenticate', {
        method: 'POST',
        body: form
    }).then((res) => {console.log(res)})

The request appears to be stopped before reaching the controller. This is 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';
});

Starting from Laravel 9.2, there seems to be a config/cors.php file that can be configured, but I don't know how. The default is as follows:

<?php

return [

    'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

];

Any idea how to allow api requests from Nuxt 3 to the auth route?

P粉739886290
P粉739886290

reply all(1)
P粉917406009

For Laravel developers, starting your SSR Nuxt journey can be very easy, especially if you write Laravel using Homestead

Your SSR Nuxt site may use example.com as the domain, and your Laravel API may also be called via the prefix http://example.com/api (routing is at routes/api.php)

Nginx configuration may be

# 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;
    }

In your SSR Nuxt3

$fetch('/api/authenticate', {
    method: 'POST',
    body: form
}).then((res) => {console.log(res)})

After that, you can save time dealing with CORS.


More information about proxy_set_header X-Forwarded-For $remote_addr; :

In SSR Nuxt, some requests are sent from the front-end server and some requests are sent from the client browser. When coming from the frontend server it may trigger Laravel throttling with its own IP instead of the client's IP, to avoid this you can add a proxy_set_header X-Forwarded-For $remote_addr;代码> first . Then add request headers to your Nuxt request.

In SSR Nuxt2 (using @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']);
    }
}

In SSR Nuxt3, axios is not required since the official HTTP client is included, please see the solution here

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template