Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
915 views
in Technique[技术] by (71.8m points)

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

How can I add csrf token with my ajax requests (GET or POST) of my Laravel application automatically without adding it manually to each and every request.

My ajax Request

   $.ajax({
      type:'post',
      url: "/email/unique",
      data: { "_token": "{{ csrf_token() }}", "email": email }
      success: function(data) {
        console.log(data);
      }
   });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
 }); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...