[英]Django CSRF Token error or missing with Ajax POST request
I am trying to integrate ajax into a web application with the Django framework.我正在尝试使用 Django 框架将 ajax 集成到 Web 应用程序中。 I am however having a hard time trying to make a simple ajax call to work.
然而,我很难尝试通过简单的 ajax 调用来工作。
I want to make a DB connection using a form (where users input the DB credentials), call the API, then return the output (whether successful or not).我想使用表单(用户在其中输入数据库凭据)建立数据库连接,调用 API,然后返回输出(无论成功与否)。
Here's my views.py that is used to handle the API:这是我用于处理 API 的views.py :
# -- START from HERE !
class TestConnectionAPI(views.APIView):
'''
Test DB Connection from TARGET DB
'''
def post(self, request):
dbs = (request.data['host'],
request.data['port'],
request.data['dbname'],
request.data['user'],
request.data['password'],
request.data['schema_name'])
try:
x = dc.DbConnection(*dbs)
x.create_conn()
data = x.check_conn()
result = {
'message' : 'Success',
'server' : f'Connection established from {data}',
'results':{
'host':dbs[0],
'port':dbs[1],
'dbname':dbs[2]
},
}
return Response(result, status=status.HTTP_200_OK)
except Exception as e:
return Response({'Message':str(e)}, status=status.HTTP_400_BAD_REQUEST)
This is my connection.html to display the form (complete code: here ) :这是我的connection.html来显示表单(完整代码: 这里):
...
<form method="post">
<div class="modal-body">
<div class="form-group">
<label for="host">Hostname</label>
<input type="text" class="form-control" id="host" name="host" aria-describedby="host">
</div>
<div class="form-group">
<label for="port">Port</label>
<input type="number" class="form-control" id="port" name="port" placeholder="e.g., 5432">
</div>
<div class="form-group">
<label for="database">Database name</label>
<input type="text" class="form-control" id="dbname" name="dbname" placeholder="Enter database name">
</div>
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="user" name="user" placeholder="Enter username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<div class="form-group">
<label for="schema">Schema</label>
<input type="text" class="form-control" id="schema_name" name="schema_name">
</div>
</div>
<div class="modal-footer border-top-0 d-flex justify-content-center">
<a href="#form2" class="btn btn-primary" data-toggle="modal" type="submit" id="btnSubmit">Test</a>
<button type="submit" class="btn btn-success">Save</button>
</div>
</form>
...
And, here's the AJAX function for calling the API (POST request):并且,这是用于调用 API(POST 请求)的AJAX 函数:
$('#btnSubmit').click(function () {
let _host = $('#host').val();
let _port = $('#port').val();
let _dbname = $('#dbname').val();
let _user = $('#user').val();
let _password = $('#password').val();
let _schema_name = $('#schema_name').val();
var $crf_token = $('[name="csrfmiddlewaretoken"]').attr('value');
$.ajax({
type: 'POST',
dataType: 'JSON',
headers:{"X-CSRFToken": $crf_token},
data:{
"host" : _host,
"port" : _port,
"dbname" : _dbname,
"user" : _user,
"password" : _password,
"schema_name": _schema_name,
},
url:"http://127.0.0.1:8000/api/v1/test/",
error: function (xhr, status, error) {
var err_msg = ''
for (var prop in xhr.responseJSON) {
err_msg += prop + ': ' + xhr.responseJSON[prop] + '\n';
}
alert(err_msg);
},
success: function (result) {
console.log(result);
}
});
});
However, I have a hard time fixing the error.但是,我很难修复错误。 I tried to follow some discussion in the StackOverflow forum, but I still have this error.
我试图遵循 StackOverflow 论坛中的一些讨论,但仍然出现此错误。 The error is related to the CSRF token , where it is difficult for me to follow the Django documentation.
该错误与CSRF 令牌有关,我很难遵循 Django 文档。
At least I want to display this API response on the console log.至少我想在控制台日志上显示这个 API 响应。
{
"message": "Success",
"server": "Connection established from ('PostgreSQL 12.7, compiled by Visual C++ build 1914, 64-bit',)",
"results": {
"host": "localhost",
"port": 5432,
"dbname": "dvdrental"
}
}
Added-1 : POST request header添加-1 :POST请求头
Could you please help me to solve the problem?你能帮我解决这个问题吗? Thanks.
谢谢。
This is what I did to fix my problem.这就是我为解决我的问题所做的。 I added some script to the main function.
我在主函数中添加了一些脚本。 By using this script, my error message: csrf token invalid or missing is resolved.
通过使用这个脚本,我的错误信息:csrf token invalid or missing 得到解决。
Edited script:编辑脚本:
<script>
// DB Connection GET method
function BindConnection(){
$.ajax({
type:"GET",
dataType: "JSON",
url: "http://127.0.0.1:8000/api/v1/test",
success: function(data){
console.log("BindConnection output:",data);
var str = "";
for (var key in data){
// console.log(data[key]);
str += "<tr>" +
"<td>" + data[key] + "</td>"
"</tr>"
}
$("#divBody").html(str);
}
});
}
// DB Connection POST method
$('#btnSubmit').click(function () {
let _host = $('#host').val();
let _port = $('#port').val();
let _dbname = $('#dbname').val();
let _user = $('#user').val();
let _password = $('#password').val();
let _schema_name = $('#schema_name').val();
// added function
function Cookies(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// 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 = Cookies('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);
}
}
});
// --- end of added function
$.ajax({
type: 'POST',
dataType: 'JSON',
data:{
"host" : _host,
"port" : _port,
"dbname" : _dbname,
"user" : _user,
"password" : _password,
"schema_name": _schema_name,
},
url:"http://127.0.0.1:8000/api/v1/test/",
error: function (xhr, status, error) {
var err_msg = ''
for (var prop in xhr.responseJSON) {
err_msg += prop + ': ' + xhr.responseJSON[prop] + '\n';
}
// alert(err_msg);
$("#divMessage").html(err_msg)
},
success: function (result) {
var str = "";
for (var key in result){
str += "<p>" + result[key] + "</p>"
}
$("#divMessage").html(str)
console.log(str)
}
});
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.