我为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:警告 - 禁止访问(CSRF令牌丢失或不正确。): / 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
})
答案 0 :(得分:1)
试试此代码
// 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);
}
}
});
答案 1 :(得分:0)
如果您不想使用CSRF令牌,只需在代码上方添加。
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def IndexView(request):
# your code