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

前端 未结 7 1570
后悔当初
后悔当初 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:57

    Generally I agree with the concept Kornel suggested except one thing.

    Yes, Laravel's docs advice to use $.ajaxSetup, but it's not recommended since this method affects all the subsequent ajax requests. It is more correctly to set the ajax settings for each request. Though you can re-set stuff:

    All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup()

    If you use $.ajax(), it's more convenient to utilize either data property or headers. Laravel allows CSRF-token both as a request parameter or a header.

    First, you add the following meta tag into the view

    
    

    And then make an ajax request either way:

    $.ajax({
        url: "/your/url",
        method: "POST",
        data:
        {
            a: 'something',
            b: 'something else',
            _token: $('meta[name="csrf-token"]').attr('content')
        },
        datatype: "json"
    });
    

    OR

    $.ajax({
        url: "/your/url",
        method: "POST",
        data:
        {
            a: 'something',
            b: 'something else',
        },
        headers: 
        {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
        datatype: "json"
    });
    

提交回复
热议问题