简体   繁体   中英

How do I make a post request from react.js front end to flask backend that sends data but also grabs data?

I am posting a user id to the backend route /stat. In /stat I want to perform a query that takes in user id as a parameter. Then I also want to get the result of the query in the front end so I can display the value. I understand how to make a post request that successfully sends the data, but how do I program it to also grab data?

my post request on the front end looks like this:

const postData = (username) => {
          try {
              let result = fetch('http://127.0.0.1:5000/stat', {
                  credentials: 'include',
                  method: 'POST',
                  mode: 'no-cors',
                  headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/json',
    
                  },
                  body: JSON.stringify({
                      user: username
                  })
              });
          } catch(e) {
              console.log(e)
          }
    }

and my backend route /stat looks like this:

@app.route('/stat', methods=['GET', 'POST'])
def stats():
  request_data = request.get_json()
  user = request_data['user']
  def get_total_percent_correct(user):
    correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)
    total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)
    return float(correct[0][0])/float(total[0][0])

  response_body = {
        "totalAccuracy": get_total_percent_correct(user),
        "user" : user
    }
  return response_body

You need to get the response from the fetch call. If you send JSON from the backend this is how it would look:

fetch('http://127.0.0.1:5000/stat', {
    credentials: 'include',
    method: 'POST',
    mode: 'no-cors',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',

    },
    body: JSON.stringify({
        user: username
    })
})
.then(function(response) {
    console.log(response.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