使用 ReactJS、Superagent 和 Python (flask) 发布

POSTing using ReactJS, Superagent and Python (flask)

我正在尝试 post 一些数据到我用 Flask 制作的 Python 后端。我在 React 组件中使用 SuperAgent。出于某种原因,我不断收到 HTTP 错误 400。

我读过许多关于使用 JQuery 和烧瓶的类似问题的 post。那里的解决方案是像我一样设置 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 function/endpoint:

@app.route('/api/leavecomments', methods=['POST'])
def comment_to_photos():
  comment = request.form['comment']
  print(comment)
  tag = request.form['tag']
...

所以对于其他有这个问题的人来说,他们需要使用名为 get_json 的方法,该方法将在 [=22] 中传递给它的值=] 格式。对于上面的代码,它正在寻找这些值作为查询字符串 post 参数,通常通过表单 posts 发送。在 AJAX JSON post 的情况下,数据存在于 request.body.

有关更多信息,请查看...

http://flask.pocoo.org/docs/0.10/api/#flask.Request.get_json