【发布时间】:2019-10-28 12:30:39
【问题描述】:
所以我尝试使用 Ajax 和烧瓶将一些 jquery 数据从前端发送到后端,但我不断收到此错误,但我所有其他代码都工作正常
我尝试使用 type: 'POST' 和 $.post 来尝试发送数据,但运气不佳。我也试过用 request.form 和 request.get_json(),还是不行。
我尝试在 postman 中运行一个快速测试,它告诉了我。我正在尝试运行 POST 请求。
邮递员的代码
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The CSRF token is missing.</p>
Python 烧瓶
#all other code is fine...
@users.route('/api/get_msg') #Both users can communicate
def get_msg():
text = Messages.query.all()
users = Users.query.all()
return jsonify([
{
"msg": text[m].message,
"user": text[m].sender.username
}
for m in range(len(text))
])
@users.route('/api/send_msg', methods=['POST'])
def send_msg():
data = request.get_json()
from_user = current_user
msg_text = data["msg_text"]
newMsg = {
"msg_text": msg_text
}
msg_log = Message(message=msg_text, sender=from_user)
db.session.add(msg_log)
db.session.commit()
return jsonify({"result", "success"})
Javascript
$(function() {
var $msg_history = $('#messages');
var $msg_text = $('input #msg_text');
let $username = $('#current_user_id').data();
let $other_user = $('#to_send_user_1').data();
function incoming(text){
$msg_history.append(`
<div class="incoming_msg">
<div class="incoming_msg_img"> <img src="https://ptetutorials.com/images/user-profile.png" alt="sunil"> </div>
<div class="received_msg">
<div class="received_withd_msg">
<p><strong>${text.user}</strong>: ${text.msg}</p>
<span class="time_date">16:09 | Today</span></div>
</div>
</div>
`);
}
function outgoing(text){
$msg_history.append(`
<div class="outgoing_msg">
<div class="sent_msg">
<p>${text}</p>
<span class="time_date"> 11:00am </span> </div>
</div>
`);
}
$.ajax({
type: 'GET',
url: '/api/get_msg',
success: function(data){
$.each(data, function(i, msgs){
incoming(msgs);
});
},
error: function(){
alert('ERROR: Could not load messages. Please try to reconnect.')
}
});
// SEND MSG
var $sendBtn = $('#send_btn');
var $msg_text = $('#msg_text');
$sendBtn.on('click', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: '/api/send_msg',
data: {
"msg_text": $msg_text.val()
}
})
.done(function(data){
if (data.error){
outgoing('Could Not Send');
}
else{
outgoing($msg_text.val());
}
});
$msg_text.val('');
});
});
HTML 或 Jinja2 模板
<div class="mesgs">
<div class="msg_history" id="messages">
<!-- Some other Code-->
</div>
<div class="type_msg" id="messageInput">
<div class="input_msg_write">
<input type="text" class="write_msg" id="msg_text" name="msg_text" placeholder="Type a message" />
<button class="msg_send_btn" id="send_btn" type="button">Send</button>
</div>
</div>
</div>
我正在尝试让后端将消息保存到数据库,然后通过 get 请求将其发送回前端。就像一个聊天应用程序。
我也在尝试找出使用flask 和jquery 创建即时聊天应用程序的最佳方式。如果有人有一些建议。请告诉我。我已经在使用 pusher 来实时推送消息了。
【问题讨论】:
-
HTTP 错误 400 通常意味着您的请求中缺少某些必需参数,或者无效。
标签: javascript python jquery html flask