'I got No 'Access-Control-Allow-Origin' header is present on the requested resource error

Making request from @vue/cli 4.5.8 app to my laravel ( Laravel Framework 8.24.0 with hosting http://local-backend-currencies.com ) backendpoint app I got error in the console

Access to XMLHttpRequest at 'http://local-backend-currencies.com/login' from origin 'http://localhost:8080' 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.

On client part :

console.log('+login settingCredentialsConfig::')
console.log(settingCredentialsConfig)

axios.post(apiUrl + '/login', userCredentials, settingCredentialsConfig)
  .then((response) => {

settingCredentialsConfig is defined :

export const settingCredentialsConfig = {
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Credentials': true
    // Authorization: -1
  }
}

and in src/main.js :

import axios from 'axios'
axios.defaults.crossDomain = true

and on laravel part in composer.json:

"license": "MIT",
    "require": {
    "php": "^7.3",
    "fruitcake/laravel-cors": "^2.0",
    "tymon/jwt-auth": "^1.0",
},

In config/auth.php :

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],

],

In app/Http/Kernel.php :

<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,  // I ADDED THIS LINE
        \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

    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,
        ],

        'api' => [
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,


        'jwt.auth' => 'Tymon\JWTAuth\Middleware\GetUserFromToken', // I ADDED THIS LINE
        'jwt.refresh' => 'Tymon\JWTAuth\Middleware\RefreshToken'   // I ADDED THIS LINE
    ];
}

In config/cors.php :

<?php

return [


    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],


    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];

I cleared cahce and dumped composer.

What did I miss ?

Thanks!



Solution 1:[1]

One easiest way to do this is by adding this code to the beginning of your API route file (api.php)

//header parameters to allow external server to access
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Origin, Authorization, Accept, X-Requested-With');

Solution 2:[2]

I ran into similar issues (I had set everything correctly in the cors.php file) and in my case, the fix was as follows:

  1. Before anything else, rung: php artisan optimize

  2. I had dd() in my code which was breaking the Middleware flow.

    Ref: If you echo(), dd(), die(), exit(), dump() etc in your code, you will break the Middleware flow.

  1. Another case: My bootstrap/cache folder didn't have proper permissions. I updated permission to 775 which fixed the issue for me.

    chmod 775 bootstrap/cache -R

    php artisan optimize

  2. Also, I made sure that there is no additional Access-Control-Allow-Origin present in the .htaccess file.

Solution 3:[3]

It is because you want to access a remote location http://local-backend-currencies.com from your localhost via JS - and this is prohibited.

To call the login you should call http://localhost:8080/login. I tink you call the Laravel backend from your local development env localhost:8080 - which is a bad idea.

I am unsure how CORS is set up in your application, what package you use for it, but if really everything is ok you should allow localhost:8080. If you use Laravel 7+ see the docs about this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Promise Shedrach
Solution 2 Md. Zubaer Ahammed
Solution 3