我已经开发了一个项目,在Django中发送AJAX请求发送到服务器。 我在ajax中使用了csrf标记,我的项目运行得很好。 当我将我的项目复制到另一台机器并在那里运行时,问题就出现了。 以下错误出现:CSRF cookie未设置错误
Forbidden (CSRF cookie not set.)
两台机器上运行得很好,有Django的几乎相同的配置。有没有人有任何想法这个问题出现? 以下是我的ajax:
var csrftoken = Cookies.get('csrftoken');
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);
}
}
});
var $chatlog = $('.js-chat-log');
var $input = $('.js-text');
var $sayButton = $('.js-say');
function createRow(text) {
var $row = $('<li class="list-group-item"></li>');
$row.text(text);
$chatlog.append($row);
}
function submitInput() {
var inputData = {
'text': $input.val()
}
// Display the user's input on the web page
createRow(inputData.text);
var $submit = $.ajax({
type: 'POST',
url: chatterbotUrl,
data: JSON.stringify(inputData),
contentType: 'application/json'
});
$submit.done(function(statement) {
createRow(statement.text);
// Clear the input field
$input.val('');
});
$submit.fail(function() {
// TODO: Handle errors
});
}
$sayButton.click(function() {
submitInput();
});
$input.keydown(function(event) {
// Submit the input when the enter button is pressed
if (event.keyCode == 13) {
submitInput();
}
});
请注意,项目运行一台机器上完全没问题(Django的1.10版),并且不能运行任何其他机器上(版本1.9.4)
您是否提到过
?? @jatinbhola – PassionInfinite我不使用表单发送请求。通过单击按钮发送请求 –
您使用安全(https)url还是本地? – PassionInfinite