【Django|csrftoken】获取csrftoken的函数
详见Django源码分析班7.09约25分钟前后处
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// 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;
}
—————————————————————————————
关于Ajax中传递csrftoken值的些许问题记录
总结:
1.前端中,尤其是ajax中,使用横杠,而非下划线
2.视图函数中,使用下划线,而非横杠,且字母都得大写
———————————————————————————
1.在Ajax中,headers中,提交的请求头,必须使用-作为分隔,而非_

此处先以错误作为展示,使用_
浏览器后台可以看处错误之处

视图函数如下

再看django后台的日志记录

2.修改下划线为横杠,如下图

看浏览器后台

再看django后台

xxxx_123没有数据,是因为,在ajax中,使用的是下划线,而非横杠
修改后如下

—————————————————————
如果每个ajax请求都这么写,略显麻烦,可以类似于python的装饰器,写个在每次ajax请求发送数据前必须执行的函数,如下
function bindSendSmsEvent(){
$.ajaxSetup({
beforeSend:function (xhr,settings){
xhr.setRequestHeaders('X-CSRFTOKEN',getCookie('csrftoken'));
}
})
}
———————————————————————————————-
上面的函数,仍有不足,因为GET之类的方法,是不需要携带csrftoken的,再次优化如下
function csrfSafeMethod(method){
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function bindSendSmsEvent(){
$.ajaxSetup({
beforeSend:function (xhr,settings){
if (!csrfSafeMethod(settings.type)){
xhr.setRequestHeaders('X-CSRFTOKEN',getCookie('csrftoken'));
}
}
})
}
———————————————————–
另外,其他的html页面可能也需要,故而可以让它单独做个模块引入即可。

/**
* 根据cookie的name获取对应的值
* @param name
* @returns {null}
*/
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// 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;
}
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)) {
xhr.setRequestHeader("X-CSRFTOKEN", getCookie('csrftoken'));
}
}
})