简体   繁体   English

尝试将JSON数据发布到python flask服务器中的问题

[英]Problems in trying to POST json data to python flask server

I am trying to Post a json to my flask server, but the post request always fails. 我试图将json发布到我的Flask服务器,但是发布请求始终失败。 This is how I am doing it, any idea what is am doing wrong? 这就是我的做法,知道做错了什么吗?

jQuery.ajax({
    url:'/someLink',
    method:'POST',
    data:JSON.stringify({"sampleKey":"Value"}),
    success:function(data){
        console.log(data);
    },
});

And my flask server looks something like 我的烧瓶服务器看起来像

@app.route('/someLink', methods=['POST'])
def someFn():
 sampleKey = str(request.form['sampleKey'])

I believe there is some data serializing issue, as the following request works 我认为存在一些数据序列化问题,因为以下请求有效

jQuery.post('/someLink',{"sampleKey":"Value"},function(data){console.log(data)});

jQuery's .ajax accepts either a plain object, or a query string as parameters for data. jQuery的.ajax接受纯对象或查询字符串作为数据参数。 It does not accept JSON encoded strings. 它不接受JSON编码的字符串。

It sends the data as 'application/x-www-form-urlencoded; charset=UTF-8' 它以'application/x-www-form-urlencoded; charset=UTF-8'发送数据'application/x-www-form-urlencoded; charset=UTF-8' 'application/x-www-form-urlencoded; charset=UTF-8' by default, which means unless you explicitly override this like Ian suggested possible (and the server is expecting it) you should not pass a JSON encoded string. 默认情况下为'application/x-www-form-urlencoded; charset=UTF-8' ,这意味着除非您像Ian建议的那样(并且服务器期望这样做)明确覆盖此内容,否则您不应传递JSON编码的字符串。

You can resolve this easily by passing the object. 您可以通过传递对象来轻松解决此问题。

From the API API

data 数据

Type: PlainObject or String 类型:PlainObject或字符串

Data to be sent to the server. 数据要发送到服务器。 It is converted to a query string, if not already a string. 如果还不是字符串,则将其转换为查询字符串。 It's appended to the url for GET-requests. 它被附加到GET请求的URL上。 See processData option to prevent this automatic processing. 请参阅processData选项以防止这种自动处理。 Object must be Key/Value pairs. 对象必须是键/值对。 If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). 如果value是一个Array,则jQuery会根据传统设置(如下所述)的值,使用相同的键序列化多个值。

Try 尝试

jQuery.ajax({
    url:'/someLink',
    method:'POST',
    data:{"sampleKey":"Value"},
    success:function(data){
        console.log(data);
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM