1

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.

Pc Monk
  • 75
  • 2
  • 4
  • 24
  • 2
    Your CORS middleware should come first, before any auth middleware (because preflight requests never send credentials). – jub0bs Dec 28 '21 at 09:42
  • Thanks,I have done that and performed a config:cache – Pc Monk Dec 28 '21 at 09:45
  • Did it solve the issue? If not, has the CORS error message changed? – jub0bs Dec 28 '21 at 09:47
  • the error is exactly the same `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.` – Pc Monk Dec 28 '21 at 09:50
  • @PcMonk what's with the `proxy` in the `nuxt.config.js`? – Script47 Jan 03 '22 at 04:56
  • Im trying to use the proxy in nuxt.config to avoid CORS https://axios.nuxtjs.org/options/#proxy – Pc Monk Jan 03 '22 at 05:45
  • Hi are you using laravel mix or browsersync for your project development? – umefarooq Jan 03 '22 at 06:35
  • @PcMonk You should get rid of that proxy; it's likely to bring more confusion than help. If you control the server, you can "solve" your CORS problem just by configuring it right. Start from the beginning without that proxy. – jub0bs Jan 03 '22 at 07:55
  • Im not using Laravel mix, Also I have configured wamp to accept CORS and deleting the proxt part would return the same error @jub0bs – Pc Monk Jan 03 '22 at 10:10
  • Same issue i was facing laravel livewire, mix and browser sync and i followed information on following link worked for me https://warrickbayman.medium.com/browsersync-and-inertia-8e3ed647669a hope this give you some idea. – umefarooq Jan 03 '22 at 12:04
  • Have you tried enabling `headers_module` of the apache server? – tpbafk Jan 03 '22 at 13:52
  • 1
    Please add your Nginx or Apache configuration. – Ricardo Vargas Jan 05 '22 at 05:58
  • @PcMonk Please add screenshots of the CORS request and response from your browser's Network tab. – jub0bs Jan 07 '22 at 11:04

2 Answers2

1

You may check if there's any abnormal response like die(...), dd(..) or exit. These methods also may trigger cors error.

devcrazy
  • 505
  • 5
  • 14
-1

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

Pc Monk
  • 75
  • 2
  • 4
  • 24