我正在开发一个网站,该网站跟踪待办事项列表并从服务器中提取它。 下面有两个 ajax 调用示例。任务 GET 调用工作正常,但添加 POST 却不行。由于某种原因,它给了我一个 403 禁止错误,因此不执行代码。
我正在查看403 Forbidden error when making an ajax Post request in Django framework 我阅读了 @yohn 发布的链接,但我不明白如何实现这个解决方案。
var tasker = (function() {
return {
tasks : function( ownerId, cb ) {
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'GET',
success: function(task) {
if(task){
var list = []
for(var a=0; a<task.length; a++){
var newTask = {
onwerId: task[a].ownderId,
desc: task[a].desc,
due: new Date(task[a].due),
color: task[a].color,
complete: task[a].complete,
id: task[a].id
};
list.push(newTask);
}
cb(list , null);
}
else{ cb(null, 'error retreiving your tasks');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
},
add : function( ownerId, task, cb ) {
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'POST',
success: function(task) {
var d = new Date(task.due);
if(task){
var newTask = {
onwerId: task.ownderId,
desc: task.desc,
due: d,
color: task.color,
complete: task.complete,
id: task.id
};
cb(newTask , null);
}
else{cb(null, 'error adding your task');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
},
}
})();
最佳答案
Django 在发出 POST 请求时需要一个 csrf
token (除非您使用基于 token 的身份验证,但我假设您不在这里)。就像您需要在表单提交中包含 {{ csrf_token }}
一样。
有关您需要它的原因以及 csrf token 用途的更多信息:What is a CSRF token ? What is its importance and how does it work?
因此,对于您的问题,请将 add
下的 ajax 调用更改为:
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'POST',
data: { csrfmiddlewaretoken: '{{ csrf_token }}'}, // added csrf token.
success: function(task) {
var d = new Date(task.due);
if(task){
var newTask = {
onwerId: task.ownderId,
desc: task.desc,
due: d,
color: task.color,
complete: task.complete,
id: task.id
};
cb(newTask , null);
}
else{cb(null, 'error adding your task');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
关于javascript - 错误 403 禁止通过 ajax 进行服务器请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41175787/