Im trying to run a Laravel V8.14(Backend) and nuxtJS 2.15(Frontend) app but unfortunately every API request (including SSR ones) are getting CORS policy error on my LOCAL computer using WAMP
Running npm run dev
everything gets compiled and it starts listening on http://localhost:3000/ .
No Errors on the console or command prompt when Im trying to access my homepage.but the api requests getting CORS policy error.
I have tried baseURL and proxy with nuxtJS but the error stay the same all the time.I am aware you cannot have these two at the same time
Laravel cors.php config file
<?php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS Options
|--------------------------------------------------------------------------
|
| The allowed_methods and allowed_headers options are case-insensitive.
|
| You don't need to provide both allowed_origins and allowed_origins_patterns.
| If one of the strings passed matches, it is considered a valid origin.
|
| If array('*') is provided to allowed_methods, allowed_origins or allowed_headers
| all methods / origins / headers are allowed.
|
*/
/*
* You can enable CORS for 1 or multiple paths.
* Example: ['api/*']
*/
'paths' => ['api/*'],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins. Wildcards can be used, eg `*.mydomain.com`
*/
'allowed_origins' => ['*'],
/*
* Patterns that can be used with `preg_match` to match the origin.
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header with these headers.
*/
'exposed_headers' => [],
/*
* Sets the Access-Control-Max-Age response header when > 0.
*/
'max_age' => 0,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
];
nuxt.config.js file
axios:{
//baseURL : process.env.CLIENT_URL, //Cant be used with proxy
proxy:true,
browserBaseURL: process.env.CLIENT_URL + '/api', // client url
prefix: '/api/',
common: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
}
},
proxy: {
'/api/': { target: 'http://api.localhost/', pathRewrite: {'^/api/': ''}, changeOrigin: true }
},
Laravel Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\SetLocale::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
// \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
// \Illuminate\Session\Middleware\StartSession::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
// \Illuminate\View\Middleware\ShareErrorsFromSession::class,
// \App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'minify' =>[
\RenatoMarinho\LaravelPageSpeed\Middleware\InlineCss::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\ElideAttributes::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\InsertDNSPrefetch::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\RemoveComments::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\TrimUrls::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\RemoveQuotes::class,
\RenatoMarinho\LaravelPageSpeed\Middleware\CollapseWhitespace::class,
],
'api' => [
//'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'admin' => \App\Http\Middleware\Adminmiddleware::class,
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
The Exact Error
Access to XMLHttpRequest at 'http://localhost/api/dashboard/getusercompanyfresh'
from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
All the API requests are in laravel api.php in routes folder
Its been 5 days Im stuck in this and mostly Im changing stuff with proxy hoping it works next time.even did a fully fresh installation of nuxtJS(removing node_modules and package.json.lock) but no luck.
Any help would be greatly appreciated.
The problem was my wamp apache
configuration, I'll be explaning the steps I took in order to find what was causing CORS error and how I fixed it.
After installing everything on a fresh windows I was still facing the issue but NOT on a live server so I've figured it must be the web server I'm running and that was the issue.The wrong part of my apache configuration on WAMP was :
DocumentRoot "${INSTALL_DIR}/www/laravel/"
<Directory "${INSTALL_DIR}/www/laravel/">
which I had in both httpd.conf and httpd-vhosts.conf.After changing the above to (adding the public folder of laravel) :
DocumentRoot "${INSTALL_DIR}/www/laravel/public"
<Directory "${INSTALL_DIR}/www/laravel/public">
Everything started working with the SAME configuration in the question that I posted and CORS policy error was gone.
I have also tested another method which you can remove the proxy and the axios setting in the nuxt.config.js file will be the following :
axios:{
baseURL : process.env.CLIENT_URL, //Cant be used with proxy
browserBaseURL: process.env.CLIENT_URL + '/api', // client url
common: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json, text/plain, */*',
}
},
where CLIENT_URL is a .env laravel file variable and its value is http://localhost
in my case and anything proxy related should be commented because you cannot use proxy and baseURL at the same time.
Read More about nuxt axios module here
Keep in mind that you have to have LoadModule headers_module modules/mod_headers.so
known as headers_module
uncommented in your httpd.conf too
Thanks for all the help along the way