简体   繁体   中英

I can't access the data in my axios post request

I'm trying to access the data I stored in localStorage so I can use it in my Python route.

Here's my axios request:

if ($('.box.genre').length === $('.box.genre.completed').length) {
    async function getScore() {
      let score = parseInt(localStorage.getItem("score"));
      const response = await axios.post(
        `${BASE_URL}/game-over`, { "score": score}, {
          headers: {
            'content-type': 'application/json'
          }
        }).then(response =>
          localStorage.getItem("score", response.data.score));
      console.log('Your score was: ', response);
     window.location = "/game-over";
    }
    getScore();  
  }

When I console log the response I'm able to see the score. My Python code doesn't seem to be working. I'm unable to get the data. I get an AttributeError: 'NoneType' object has no attribute 'content'.

Here's my Python:

@app.route('/game-over', methods=["GET", "POST"])
def game_over():

  if CURR_USER_KEY in session:
    user = User.query.get(session[CURR_USER_KEY])

  response = request.json()
  data = json.loads(response.content)
  score = data['score']

  user.high_score = score
  db.session.commit()

  high_score = user.high_score
  name = user.username

  return render_template('endgame.html', name=name, high_score=high_score)

I'm just trying to get the score from axios so I can update my SQL table. Thanks so much for the help!

There are 2 problems in your code.

First : If you want to set an item in local storage you must use setItem instead getItem

Second : When you use an async function, You do not need to use .then

async function getScore()
 const response = await axios.post(
  `${BASE_URL}/game-over`,
  { 'score': score },
  { headers: { 'content-type': 'application/json' }
 })

 if (response) {
  localStorage.setItem('score', response.data.score)
 }
}

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