Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jelly's avatar
Level 1

Blocked cross origin request -> missing x-csrf-token

I want to fill a select with countries. To do that i call the api https://restcountries.eu/rest/v2/all?fields=name

I get the following error -> Cross Origin request blocked: The same source-rule forbids reading the external ressource https://restcountries.eu/rest/v2/all?fields=name. (Reason: missing token 'x-csrf-token' in CORS-Heder 'Access-Control-Allow-Headers' from CORS-Preflight-Channel)

I did the following

Included the csrf-token in a meta tag in the head

<meta name="csrf-token" content="{{ csrf_token() }}">

Included the cors middleware from https://github.com/barryvdh/laravel-cors

This is what my script looks like

$(document).ready(function () {

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        type: 'get',
        url: 'https://restcountries.eu/rest/v2/all?fields=name',
        success: function (result)
        {
            
        },
        error:function()
        {
            console.log("something went wrong");
        }
    });
});

0 likes
3 replies
bobbybouwmann's avatar

Your code looks correct to me. So two questions for you:

  1. Are you sure $('meta[name="csrf-token"]').attr('content') is returning the correct token?
  2. Have you tried passing the headers to the ajax request alone and check if that works?

You can see in your browser console if the header was send with the request or not! That might be a good starting point to look where this is going wrong

NielsNumbers's avatar

The error message is telling you that the API that you are using in not allowing X-CSRF-TOKEN. You should only set the X-CSRF-TOKEN when you call an intern url from your laravel application.

Just change your code to:

$(document).ready(function () {
    $.ajax({
        type: 'get',
        url: 'https://restcountries.eu/rest/v2/all?fields=name',
        success: function (result)
        {
            
        },
        error:function()
        {
            console.log("something went wrong");
        }
    });
});

If you have set the header in a different .js file with $.ajaxSetting you may remove it using

delete $.ajaxSettings.headers["X-CSRF-TOKEN"];

just before your ajax call.

Please or to participate in this conversation.