简体   繁体   English

使用ReactJS,Superagent和Python进行发布(烧瓶)

[英]POSTing using ReactJS, Superagent and Python (flask)

I'm trying to post some data to a Python backend that i made with Flask. 我试图将一些数据发布到用Flask制作的Python后端。 I'm using SuperAgent in a React component. 我在React组件中使用SuperAgent For some reason i keep getting HTTP error 400. 由于某种原因,我一直收到HTTP错误400。

I've read many posts about similar problems using JQuery and flask. 我已经阅读了许多有关使用JQuery和flask的类似问题的文章。 The solution there is to set the contentType the same way i have and also JSON.stringify the data. 那里的解决方案是以与我相同的方式设置contentType,并且还对数据进行JSON.stringify。 I've tried stringify but it doesn't change anything. 我已经尝试过字符串化,但是它什么都不会改变。 Still getting an HTTP 400. 仍然获得HTTP 400。

Any ideas? 有任何想法吗?

JS code: 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: Python函数/端点:

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

So the issue for anybody else that has this problem, they need to use method named get_json which will have the values being passed to it in JSON format. 因此,对于任何其他遇到此问题的人来说,他们需要使用名为get_json的方法,该方法将以JSON格式将值传递给它。 In the case of the code above it was looking for those values as a query string post parameters, which is typically sent via form posts. 在上面的代码中,它正在寻找那些值作为查询字符串发布参数,通常通过表单发布发送。 In the case of an AJAX JSON post, the data exists inside the request.body. 对于AJAX JSON帖子,数据存在于request.body内部。

For more information check out... 有关更多信息,请查看...

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

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

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