【问题标题】:flask does not return JSON data using request.json烧瓶不使用 request.json 返回 JSON 数据
【发布时间】:2021-02-22 07:11:23
【问题描述】:

我想将输入元素的文本内容作为 json 类型发送到烧瓶并打印出值
但是 print 的输出是None

发送我使用的数据 jQuery post 方法

function upload_postdata() {
    let input_text = $("#input_element").val();
    return $.post('/upload_columns',{
        contentType: "application/json; charset=utf-8",
        data: input_text
    });
}

路线是

@flask_class.route('/upload_columns', methods=['POST'])
def upload_columns():
    date_from = request.json #
    print(f"the name is{date_from}")
    return jsonify(" polo")

阅读文档 request.json 应该返回解析的 JSON 数据。

来自浏览器的 Header 部分 也告诉我

contentType: application/json
data: Marco

那么为什么我得到 None 作为回报 使用request.json?

虽然使用 request.form['data'] 给了我正确的输出

【问题讨论】:

  • 您是否在服务器端打印了request.headers

标签: javascript python jquery json flask


【解决方案1】:

两个问题。一是您将$.post 的语法与$.ajax 的语法混合在一起。 $.ajax 接受 datacontentType 参数作为选项对象中的字段; $.post 做的事情不同,并希望将数据作为第二个参数发布。因此,您不发送任何内容类型标头,并且您的数据是两个字段,其中一个名为 data。这就是request.form["data"] 阅读它的原因。它不是 JSON,它是在 URL 编码中编码的,类似于:

contentType=application%2Fjson%3B%20charset%3Dutf-8&data=Marco

如果你改用了$.ajax,它仍然无法工作,因为jQuery 不会自动将data 转换为JSON,并且Marco 不是有效的JSON — "Marco" 是。要将响应转换为有效的 JSON,您需要使用

data: JSON.stringify(input_text)

这样,payload就变得简单了

"Marco"

它不能再被request.form["data"] 解析,但应该使用request.json 给出Marco

【讨论】:

  • 在烧瓶视图上使用JSON.stringify 仍然返回None,使用带有括号的jQuery Ajax and and post method, also request.json() 测试无效,返回一个TypeError。
  • 是的,全部从头输入,没有经过测试。 .json.get_json(),而不是 .json()。您不能同时获得NoneTypeError
猜你喜欢
  • 2012-12-22
  • 2020-06-27
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 2023-04-04
  • 2013-11-18
  • 1970-01-01
相关资源
最近更新 更多