phplaravel.htaccesscorslaravel-10

Laravel 10 CORS issue


I get below error in Laravel 10

Access to XMLHttpRequest at 'https://member.dev.mydomain.com/members/fernando/basic' from origin 'https://admin.dev.mydomain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'https://admin.dev.mydomain.com, https://admin.dev.mydomain.work', but only one is allowed.

This is my kernel.php

protected $middleware = [
        \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \App\Http\Middleware\TrimStrings::class,
        // \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        // \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
        // \Illuminate\Session\Middleware\StartSession::class,
        // \App\Http\Middleware\PreflightResponse::class,
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Http\Middleware\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        //\App\Http\Middleware\EncryptCookies::class,
        //\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        //\Illuminate\View\Middleware\ShareErrorsFromSession::class,
        // \Illuminate\Foundation\Http\Middleware\VerifyPostSize::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    ];

This is my config/cors.php

<?php

return [

    'paths' => ['*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*.dev.mydomain.com'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,
];

Can someone helps me to fixed this in Laravel 10?


Solution

  • Are you sure you didn't accidentally send an AJAX request from .com to .work? Your config doesn't contain the .work domain, but the error message says it was present in the HTTP header of the response.

    If your requests are all within the .com domain, perhaps you cached your config file and the changes are not reflected? You can do ./artisan config:clear to get rid of the cached config.

    The CORS headers from the response (server) tell your browser what it's allowed to send and where. If they don't match the request of your browser, your browser will automatically cancel the request to avoid abuse.
    I know wildcards in CORS can be finicky. You can inspect your request and response headers in network tab of your devtools when your browser sends the OPTION request and see if there's a missing value in the response headers. If you find any discrepancies you might want to try adding them to your config file instead of the wildcard.