charnould
charnould

Reputation: 2917

res.redirect() doesn't work except with CTRL-R: a caching issue?

I think I have a kind of "cache problem" with Express (I use Google Datastore as a DB).

When the delete route below is triggered:

My delete route:

router.post('/delete', async (req, res) => {
  await deleteOneHouse(req.params.houseID)
  res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate')
  res.redirect('/dashboard')
})

If needed, the deleteOnHouse func.

async function deleteOneHouse(ID) {
  try {
    const houseKey = datastore.key(['data', ID])
    datastore.delete(houseKey).then(() => {
      console.info(`House ${ID} deleted`)
      return
    })
  } catch (e) {
    console.error(e)
  }
}

Do you have any clue? Thanks.

Upvotes: 0

Views: 85

Answers (1)

charnould
charnould

Reputation: 2917

console.log() is surely your friend to debug.

The res.redirect() was triggered BEFORE the end of delete op. Add an await and it works fine.

Post route to delete:

router.post('/delete', async (req, res) => {
  // Delete this house
  await deleteOneHouse(req.params.houseID)
  // Redirect to Dashboard
  res.redirect('/dashboard')
})

Delete func.

async function deleteOneHouse(ID) {
  try {
    const houseKey = datastore.key(['data', ID])
    const deleted = await datastore.delete(houseKey)
    console.info(`House ${ID} deleted`)
    return
  } catch (error) {
    console.error(error)
  }
}

Upvotes: 1

Related Questions