我正在尝试向django发出ajax post请求,这是js代码片段
const xhr = new XMLHttpRequest();
console.log(xhr.readyState);
xhr.open('POST', '');
var data = '{% csrf_token %}';
console.log(data);
console.log(typeof(data));
xhr.setRequestHeader('X-CSRF-Token', data);
xhr.onload = function(){
console.log(xhr.readyState);
console.log(xhr.status);
if(xhr.status == 200){
console.log(JSON.parse(xhr.responseText));
}else{
console.log("Something went wrong!!");
}
}
xhr.send({'userId' : userId})
}
这是我的错误日志:

我收到了一个403禁止错误,有人能帮我吗?
发布于 2021-03-07 10:01:59
此函数将为您提供csrf-token
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;
}然后:
const csrftoken = getCookie('csrftoken');以获取csrf-token。
同样值得关注的是更改X-CSRF-Token
xhr.setRequestHeader('X-CSRF-Token', data);到X-CSRFToken令牌
xhr.setRequestHeader('X-CSRFToken', data);希望这能有所帮助
https://stackoverflow.com/questions/66512218
复制相似问题