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
?
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 prefixhttp://example.com/api
(routing is atroutes/api.php
)Nginx configuration may be
In your SSR Nuxt3
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
In SSR Nuxt3, axios is not required since the official HTTP client is included, please see the solution here