简体   繁体   中英

Flask JSON post request not working

I am using react to submit a form to a flask backend. The data is submitted in json this is an example.

add_new_user(e){
  e.preventDefault()
  var user_details = {}
  user_details['fname'] = this.state.first_name
  user_details['last_name'] = this.state.last_name

var post_request = new Request('http://127.0.0.1:5000/add_new_user', {
    method: 'post',
    body: JSON.stringify(user_details)
})

fetch(post_request).then(function(response){
    console.log(response)
})

On my backend the code looks like this,

@app.route('/add_new_user', methods=['POST'])
def add_user():
    content = request.json()
    print content
    return 'user added'

However the content variable is null and therefore the printed data on the screen is None. How can I fix this? What am I doing wrong. Thanks

You might need to set the request content type of Request to application/json . Otherwise, it'll be None .

Try request.get_json(force=True) . It's recommended to use get_json() instead of the json() method. force=True allows to ignore content type requirement.

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