【问题标题】:Why am I unable to get response from my API in django rest framework via jquery?为什么我无法通过 jquery 从 django rest 框架中的 API 获得响应?
【发布时间】:2016-06-07 10:42:40
【问题描述】:

我正在使用 Django REST 框架来创建 API。它与 cURL 配合得很好。

curl -H 'Accept: application/json; indent=4' -u ratan:qazwsxedc123 http://127.0.0.1:8000/api/grocery/subcategories/

但是,当我尝试使用 jQuery 在 HTML 页面中填充 div 时,它不起作用,我收到 403 禁止错误。

这是我的代码。

$.ajax({
  url: "http://127.0.0.1:8000/api/grocery/subcategories/?format=json",
  type: "GET",
  dataType: "json",
  data: {
    username: "ratan",
    password: "qazwsxedc123"
  },
  success: function(data) {
    console.log('ratan');
  },
});

我认为可能是因为 CORS,所以我尝试了django-cors-headers,但没有帮助。

【问题讨论】:

  • 尝试添加contentType: "application/json",,因为看起来您正在尝试发送 json 对象。但是,在您的 CURL 中,您再次将它们发送到标题中。
  • 这真的不是 Django 问题。
  • @DanielRoseman 问题出在他的 JS 中,但最好了解上下文的所有细节。他可能在某个地方错误地配置了他的 DRF。

标签: jquery json ajax django django-rest-framework


【解决方案1】:

您在提出请求时错误地传递了您的用户名和密码。这在this SO question 中进行了讨论。

试试这个方法。

$.ajax
({
  type: "GET",
  url: "http://127.0.0.1:8000/api/grocery/subcategories/?format=json",
  dataType: 'json',
  headers: {
    "Authorization": "Basic " + btoa("ratan:qazwsxedc123")
  },
  success: function (){
    console.log('ratan'); 
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2015-08-29
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多