【问题标题】:What's wrong with my tastypie POST request?我的 sweetpie POST 请求有什么问题?
【发布时间】: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 一起工作的方式。

标签: python django tastypie


【解决方案1】:

401 通常表示您无权访问该资源,或者存在 CSRF 问题。

想到两件事

  1. 您未通过身份验证。您是否已登录(SessionAuthentication),或者您是否在请求中发送用户名和 api 密钥(ApiKeyAuthentication)。

  2. 如果 #1 不是问题,那么可能是因为尚未设置 csrf 令牌。 Django 不会为所有请求设置令牌。来自docs -

如果您的视图未呈现包含 csrf_token 模板标签的模板,则 Django 可能不会设置 CSRF 令牌 cookie。这在表单被动态添加到页面的情况下很常见。为了解决这种情况,Django 提供了一个视图装饰器来强制设置 cookie:ensure_csrf_cookie()

我猜#2 更像是场景。您可以将视图包装在 ensure_csrf_cookie 装饰器中,或者使用中间件对所有请求执行此操作。或者您可以使用 api 密钥进行身份验证,因为它看起来不像检查 csrf 令牌(不太确定,但我正在查看 sweetpie 代码,但没有看到任何 csrf 检查。)

【讨论】:

    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 2015-11-30
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 1970-01-01
    相关资源
    最近更新 更多