简体   繁体   中英

POSTing using ReactJS, Superagent and Python (flask)

I'm trying to post some data to a Python backend that i made with Flask. I'm using SuperAgent in a React component. For some reason i keep getting HTTP error 400.

I've read many posts about similar problems using JQuery and flask. The solution there is to set the contentType the same way i have and also JSON.stringify the data. I've tried stringify but it doesn't change anything. Still getting an HTTP 400.

Any ideas?

JS code:

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']
...

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. 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.

For more information check out...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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