【问题标题】:How do I fix this with flask and jquery? HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax如何用烧瓶和 jquery 解决这个问题? HTTP400: BAD REQUEST - 由于语法无效,服务器无法处理请求
【发布时间】: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


【解决方案1】:

HTTP 400 告诉您您是 missing a CSRF token。这用于验证通过表单或 JS 发送到服务器的数据。 Flask 要求它用于表单,并且不会验证数据,除非您在 Jinja 模板中包含 form.hidden_tag()

不过,我有点困惑为什么您会在这里收到错误消息。据我所知,Flask 默认情况下不会对 AJAX 请求强制执行 CSRF 令牌。而且您不会发送表单请求,对吗?您是否已经在导入CSRFProtect?如果是这样,那么这就是问题所在,您只需在发送 AJAX 请求时将该令牌包含在标头中即可。

顺便说一句,我认为您可能打算在这里使用冒号:

return jsonify({"result", "success"})

【讨论】:

  • 如何在标题中添加它?是的,我正在导入 CSRFProtect
猜你喜欢
  • 2018-12-27
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 2014-01-31
  • 2021-02-19
  • 2020-06-11
  • 2020-03-19
  • 2016-08-22
相关资源
最近更新 更多