我的打字稿文件中有一个CSRF令牌脚本,
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]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length +1));
break ;
}
}
}
return cookieValue;
}
csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$(document).ready(function() {
var csrftoken = this.getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if(!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
当我尝试运行它时,它给了我这个2错误
任何人都知道为什么?在此先感谢!!!
答案 0 :(得分:1)
您已将所有jQuery文档就绪代码放在一个奇怪的位置。
这是编译的最低版本。
class Example {
constructor() {
$(document).ready(() => {
var csrftoken = this.getCookie('csrftoken');
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!this.csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
});
}
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]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length +1));
break ;
}
}
}
return cookieValue;
}
csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
}