How to automatically add X-CSRF-TOKEN with jQuery ajax request in Laravel

懵懂的女人 提交于 2019-11-27 09:54:14

In Laravel the value of the csrf-token meta tag registers by default with the Axios HTTP library. But If you are not using this library, you will need to manually configure this behavior for your application.

To do this, store the token in a HTML meta tag

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

Then, once you have created the meta tag, you can instruct the jQuery library to automatically add the token to all the request headers.

For that add the code to the resources/js/bootstrap.js file for Laravel 5.7 and resources/assets/js/bootstrap.js for Laravel 5.6 and below versions.

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

Ajax without csrf token as it will get added automatically

$.ajax({
      type:'post',
      url: "/email/unique",
      data: { "email": email }
      success: function(data) {
        console.log(data);
    }
 }); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!