我不知道在express中,但通常CSRF令牌在cookie中,所以你需要这两个函数:
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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
然后:
var csrftoken = getCookie('csrftoken');
$.ajax({
url : formURL,
type: "POST",
data : postData,
beforeSend: function(xhr, settings){
if (!csrfSafeMethod(settings.type)) xhr.setRequestHeader("X-CSRFToken", csrftoken);
},
success:function(data, textStatus, jqXHR){
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
}
});
或者如果您不想使用jQuery,可以使用XMLHttpRequest来发出AJAX请求:
var csrftoken = getCookie('csrftoken');
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.onload = function(){
if(xhr.status === 200){
var response = JSON.parse(xhr.responseText);
console.log(response)
}
};
xhr.send(encodeURI('category=' + cat));