django文档中介绍的处理ajax post时,头中添加csrf token的方法

https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax


AJAX

While the above method can be used for AJAX POST requests, it has someinconveniences: you have to remember to pass the CSRF token in as POST data withevery POST request. For this reason, there is an alternative method: on eachXMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRFtoken. This is often easier, because many JavaScript frameworks provide hooksthat allow headers to be set on every request.

上面的方法在每个post时,都要将CSRF token作为post数据来传,不方便,可以设置一个值为CSRFtoken的X-CSRFToken头,这样就能一劳永逸。

Acquiring the token is straightforward:

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

如果嫌上述函数实现复杂,可以试试下面的实现,区别是,需要引入

JavaScript Cookie:

<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

The above code could be simplified by using the JavaScript Cookie library to replace getCookie:

var csrftoken = Cookies.get('csrftoken');



以下描述的是:给ajax设置一个头的X-CSRFToken属性,这样每次发起post时,这个X-CSRFToken属性会自动加入post的信息中。

仔细看,可以猜到:beforeSend: function是一个类似callback的函数,每当post发起时,执行这个函数。函数里的if还做了判断,如果不是同一个域的请求,就不发送csrftoken。

Setting the token on the AJAX request

Finally, you’ll have to actually set the header on your AJAX request, whileprotecting the CSRF token from being sent to other domains usingsettings.crossDomain in jQuery 1.5.1and newer:

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});




说明文档中还介绍了另外一种取csrftoken的方法:将csrftoken明文写入网页,在通过jquery取csrftoken值。

Acquiring the token if CSRF_USE_SESSIONS is True

If you activate CSRF_USE_SESSIONS, you must include the CSRF tokenin your HTML and read the token from the DOM with JavaScript:

{% csrf_token %}
<script type="text/javascript">
// using jQuery
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
</script>

这里说的是:如果if CSRF_USE_SESSIONS is True,可以直接从html页面读取token的值。而且方法非常简单。(满足一般情况)



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值