Search code examples
javascriptjquerylaravelcsrf

Cors header error with ajax request request


I am trying to make a ajax request to the musicbrainz api but keep getting a cors header error.

the error : Access to XMLHttpRequest at 'https://musicbrainz.org/ws/2/release-group/?xxxxxxx' from origin 'https://my_url' has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

code

var $artist_encoded = encodeURIComponent($artist);
var $album_encoded = encodeURIComponent($album);

$.ajax({
    type: "GET",
    url: "https://musicbrainz.org/ws/2/release-group/?query=artist:%22" + $artist_encoded + "%22%20AND%20releasegroup:%22" + $album_encoded + "%22",
    dataType: "xml",
    success: myfunction
});

Solution

  • Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources. So you must add permission to client side(ajax request) to receive response from server side.

    You can handle this issue by creating a new middleware:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        // Cors middleware for allow api access from client side 'vue project' 
        public function handle($request, Closure $next)
        {
            return $next($request)
                ->header('Access-Control-Allow-Origin','*')
                ->header('Access-Control-Allow-Methods','*')
                ->header('Access-Control-Allow-Headers','*')
            ;
        }
    }
    

    and register the new middleware in kernel.php: in middleware array add:

    protected $middleware = [
            \App\Http\Middleware\Cors::class,
        ];
    

    in route middleware array add:

    protected $routeMiddleware = ['cors' => \App\Http\Middleware\Cors::class,
        ];
    

    Finally implement this middleware into routes:

    Route::group(['middleware' => ['cors']], function () {
    //... your routes
    });
    

    As a result when adding: ->header('Access-Control-Allow-Origin','*') it means that you allow any other origin to access your app. You could just add an array of specific routes which you want to access your app. In your case I think it's ['127.0.0.1:8000']