【发布时间】:2014-06-17 22:38:06
【问题描述】:
我在尝试使用 Tastypie 在 ajax 中发帖时收到 401。我可以将 GET 记录到控制台,它们使用相同的身份验证。如何调试?
这是我的 javascript:
// sending a csrftoken with every ajax request
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: true, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
}
}
});
//this is the get request, which works fine
$.ajax({
url: "http://localhost:8080/data/api/v1/user/?format=json",
success: function(data){
console.log(data);
}
});
$(function() {
$('#newEntry').click(function() {
var table=$("#entryName").val();
var d = JSON.stringify({
"name":entry,
"user":"http://localhost:8080/data/api/v1/user/?format=json"
});
$.ajax({
type: 'POST',
data: d,
success: function(r) {console.log(r); },
error: function(r){console.log(r); },
url: 'http://localhost:8080/data/api/v1/entry/',
cache:false
});
});
});
我之前问过this 的问题,我认为这会有所帮助,但没有。它有更多上下文,即关于我用于身份验证的内容,但如果需要,我可以提供更多详细信息。
【问题讨论】:
-
只是猜测,REST 端点可能未设置为允许 POST 请求。我不知道它是如何与 TasteyPie 一起工作的,但这就是它与 DRF 一起工作的方式。