Flask JSON无法正常工作:BadRequestKeyError:400错误请求:浏览器(或代理)发送了该服务器无法理解的请求

时间:2020-06-26 14:31:27

标签: python json flask

我正在尝试使用JSON将用户输入传递到烧瓶python文件中。 这是html正文中的citizins输入元素:

<form class="networkform" method="POST">
<input name="citizens" maxlength="15" class="InputStyle" required>
<button type="submit" style="height: 40px; width: 180px; background-color: grey; color:white">send</button>
</form>

这是html文件中的jQuery函数:

$(".networkform").on('submit', function(e){
                alert("submit is working")

                $.ajax({
                    data :
                    {
                       'citizens' : $("citizens").val(),
                    },
                    type : 'POST',
                    url : '/Dash'
                })
                .done(function(data){
                        $(".outerDiv").hide()


                })

                e.preventDefault();
        });

这是.py文件中的函数:

@app.route('/Dash', methods=['POST'])
def Dash():
if request.method == 'POST':
    print("inside post")
    num_citizins = request.form['citizens']
    print(num_citizins)
    return jsonify({"msg" : "Thanks"})

这是.py文件中的主要内容:

if __name__ == "__main__":
  print 'Start'
  main()
  app.run(debug=True)
  print 'Done!'

但是由于某种原因,它根本无法工作..这是我得到的错误:

BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.

KeyError:“公民”

我已经尝试过的解决方案:

  • 使用main.li中的app.run(debug = True,threaded = True)代替了app.run(debug = True)
  • 使用了request.form.get而不是request.form
  • 从以下位置删除了method =“ post” 但是什么都行不通..每次给出不同类型的错误..您认为问题可能是什么? (如果有任何问题,我正在使用python 2.7,IDE:pyCharm,浏览器:Chrome)

1 个答案:

答案 0 :(得分:0)

Dash()函数中,更改以下行

num_citizins = request.form['citizens']

num_citizins = request.json['citizens']

您正在发送在request.json中接收到的JSON数据。您还需要将请求内容类型设置为application/json,以使.json属性起作用。

编辑

这是在jQuery中设置内容类型的方式。您只需要像这样添加contentType : 'application/json'

                $.ajax({
                    data :
                    {
                       'citizens' : $("citizens").val(),
                    },
                    type : 'POST',
                    contentType : 'application/json',
                    url : '/Dash'
                })
相关问题