无法从端点检索数据

2024-05-04 09:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经为Django集成安装了Chatterbot。我遵循简易教程的每一步,使它的端点是:http://127.0.0.1:8000/chatterbot/我下一步做的是尝试与该端点通信,看看我是否会得到任何结果。因此,我提出了如下Ajax请求:

var query = {"text": "My input statement"};

$.ajax({
    type: 'POST',
    url: "http://127.0.0.1:8000/chatterbot/",
    data: JSON.stringify(query),
    contentType: 'application/json',
    success: function (data) {
        console.log(data);
    }
});

但是,在控制台中返回的是:POST http://127.0.0.1:8000/chatterbot/ 403 (Forbidden),在运行服务器时在cmd提示符中返回的是:

csrf: WARNING - Forbidden (CSRF token missing or incorrect.): /chatterbot/ [29/Mar/2018 02:16:43] "POST /chatterbot/ HTTP/1.1" 403 2502

为什么我会犯这个错误?如何修复它以便接收来自端点的回叫?你知道吗

查看此页:

def IndexView(request):
    latest_questions = Questions.objects.all().order_by("-date_published")[:5]
    popular_questions = Questions.objects.all().order_by("-num_replies")[:5]

    return render(request, 'core/index.html',
                  {'latest_questions': latest_questions, 'popular_questions': popular_questions
                   })

Tags: httpdataobjectsrequestorderall端点query
2条回答

尝试此代码

// using jQuery
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // 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;
}
var csrftoken = getCookie('csrftoken');

var query = {
   "text": "My input statement",
   "csrfmiddlewaretoken": csrftoken
};

$.ajax({
    type: 'POST',
    url: "http://127.0.0.1:8000/chatterbot/",
    data: query,
    contentType: 'application/json',
    success: function (data) {
        console.log(data);
    }
});

一种方法是像下面这样发送csrfmiddlewaretoken

    var query = {
       "text": "My input statement",
       'csrfmiddlewaretoken': "{{csrf_token }}"
    };

另一种方法是使用@csrf_exempt装饰器

  from django.views.decorators.csrf import csrf_exempt

  @csrf_exempt
  def IndexView(request):
     # .... code.....

另一种是添加脚本

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

引用:https://docs.djangoproject.com/en/2.0/ref/csrf/

如果您不想使用CSRF令牌,只需在代码上方添加这个。你知道吗

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def IndexView(request):
    # your code

相关问题 更多 >