jQuery X-CSRF-TOKEN header in Laravel 5.4

In Laravel 5.4, we already have HTTP client configured out-of-the-box, that we can use in frontend. It is axios. In file resources\assets\js\bootstrap.js we can see the default headers that will be included in every request that we make with axios.

axios setup
axios setup

However, although jQuery is also bootstraped, the default headers for jQuery are not set. If we want to use ajax methods that jQuery provides, we can easily set the X-CSRF-TOKEN that will be used in every request. We can do that by using the .ajaxSetup() method, like this:

$.ajaxSetup({
    headers: { 'X-CSRF-TOKEN': window.Laravel.csrfToken }
});

In bootstrap.js file, it now looks like this:

jQuery setup
jQuery setup

Leave a Reply

%d bloggers like this: