我试图将一些数据发布到我用Flask制作的Python后端。我在React组件中使用SuperAgent。出于某种原因,我不断收到HTTP错误400.
我使用JQuery和flask读过很多关于类似问题的帖子。解决方案是以与我相同的方式设置contentType,并且JSON.stringify数据。我尝试过stringify但它并没有改变任何东西。仍然获得HTTP 400。
有什么想法吗?
JS代码:
request.post(link)
.set('Content-Type', 'application/json; charset=utf-8')
.send({tag: 'tag1', comment: 'Cool'})
.end(function(err, res){
console.log(res);
});
Python函数/端点:
@app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
comment = request.form['comment']
print(comment)
tag = request.form['tag']
...
答案 0 :(得分:1)
对于有这个问题的其他人来说,问题是,他们需要使用名为 get_json 的方法,这些方法将以JSON格式传递给它。在上面的代码的情况下,它正在寻找这些值作为查询字符串post参数,通常通过表单发送。对于AJAX JSON帖子,数据存在于request.body。
中有关详细信息,请查看...
http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json