且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery 将 CSRF 令牌添加到所有 $.post() 请求的数据

更新时间:2023-01-18 11:43:19

您的 $.ajaxPrefilter 方法是一种很好的方法.不过,您不需要添加标题;您只需要向 data 字符串添加一个属性.

Your $.ajaxPrefilter approach is a good one. You don't need to add a header, though; you simply need to add a property to the data string.

数据作为 $.post 的第二个参数提供,然后格式化为查询字符串 (id=foo&bar=baz&...)在预过滤器访问 data 选项之前.因此,您需要将自己的字段添加到查询字符串中:

Data is provided as the the second argument to $.post, and then formatted as a query string (id=foo&bar=baz&...) before the prefilter gets access to the data option. Thus, you need to add your own field to the query string:

var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxPrefilter(function(options, originalOptions, jqXHR){
    if (options.type.toLowerCase() === "post") {
        // initialize `data` to empty string if it does not exist
        options.data = options.data || "";

        // add leading ampersand if `data` is non-empty
        options.data += options.data?"&":"";

        // add _token entry
        options.data += "_token=" + encodeURIComponent(csrf_token);
    }
});

这会将 id=userID 变成 id=userID&_token=csrf_token.