Adding CSRFToken to Ajax request

后端 未结 9 2036
夕颜
夕颜 2020-11-27 05:40

I need to pass CSRFToken with Ajax based post request but not sure how this can done in a best way. Using a platform which internally checking CSRFToken

相关标签:
9条回答
  • 2020-11-27 06:02

    How about this,

    $("body").bind("ajaxSend", function(elm, xhr, s){
       if (s.type == "POST") {
          xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
       }
    });
    

    Ref: http://erlend.oftedal.no/blog/?blogid=118

    To pass CSRF as parameter,

            $.ajax({
                type: "POST",
                url: "file",
                data: { CSRF: getCSRFTokenValue()}
            })
            .done(function( msg ) {
                alert( "Data: " + msg );
            });
    
    0 讨论(0)
  • 2020-11-27 06:05

    Here is code that I used to prevent CSRF token problem when sending POST request with ajax

    $(document).ready(function(){
        function getCookie(c_name) {
            if(document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=");
                if(c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    if(c_end == -1) c_end = document.cookie.length;
                    return unescape(document.cookie.substring(c_start,c_end));
                }
            }
            return "";
        }
    
        $(function () {
            $.ajaxSetup({
                headers: {
                    "X-CSRFToken": getCookie("csrftoken")
                }
            });
        });
    

    });

    0 讨论(0)
  • 2020-11-27 06:12

    You can use this:

    var token = "SOME_TOKEN";
    
    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
      jqXHR.setRequestHeader('X-CSRF-Token', token);
    });
    

    From documentation:

    jQuery.ajaxPrefilter( [dataTypes ], handler(options, originalOptions, jqXHR) )

    Description: Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax().

    Read

    0 讨论(0)
  • 2020-11-27 06:13

    This worked for me (using jQuery 2.1)

    $(document).ajaxSend(function(elm, xhr, s){
        if (s.type == "POST") {
            s.data += s.data?"&":"";
            s.data += "_token=" + $('#csrf-token').val();
        }
    });
    

    or this:

    $(document).ajaxSend(function(elm, xhr, s){
        if (s.type == "POST") {
            xhr.setRequestHeader('x-csrf-token', $('#csrf-token').val());
        }
    });
    

    (where #csrf-token is the element containing the token)

    0 讨论(0)
  • 2020-11-27 06:14

    If you are working in node.js with lusca try also this:

    $.ajax({
    url: "http://test.com",
    type:"post"
    headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
    })
    
    0 讨论(0)
  • 2020-11-27 06:14

    I had this problem in a list of post in a blog, the post are in a view inside a foreach, then is difficult select it in javascript, and the problem of post method and token also exists.

    This the code for javascript at the end of the view, I generate the token in javascript functión inside the view and not in a external js file, then is easy use php lavarel to generate it with csrf_token() function, and send the "delete" method directly in params. You can see that I don´t use in var route: {{ route('post.destroy', $post->id}} because I don´t know the id I want delete until someone click in destroy button, if you don´t have this problem you can use {{ route('post.destroy', $post->id}} or other like this.

      $(function(){
        $(".destroy").on("click", function(){
             var vid = $(this).attr("id");
             var v_token = "{{csrf_token()}}";
             var params = {_method: 'DELETE', _token: v_token};
             var route = "http://imagica.app/posts/" + vid + "";
        $.ajax({
             type: "POST",
             url: route,
             data: params
        });
       });
      });
    

    and this the code of content in view (inside foreach there are more forms and the data of each post but is not inportant by this example), you can see I add a class "delete" to button and I call class in javascript.

          @foreach($posts as $post)
              <form method="POST">
                <button id="{{$post->id}}" class="btn btn-danger btn-sm pull-right destroy" type="button" >eliminar</button>
              </form>
          @endforeach
    
    0 讨论(0)
提交回复
热议问题