jQuery add CSRF token to all $.post() requests' data

前端 未结 7 1569
后悔当初
后悔当初 2020-11-30 03:02

I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.

While m

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-30 03:58

    From Laravel documentation:

    You could, for example, store the token in a "meta" tag:

    Once you have created the meta tag, you can instruct a library like jQuery to add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:

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

    So for example you can do request like below.

    Add this meta tag to your view:

    
    

    And this is an example script which you can communicate with Laravel (sends request when you click an element with id="some-id" and you can see the response in an element with id="result"):

    
    

提交回复
热议问题