Home > Mobile >  Cannot set headers after they are sent to the client while using res.redirect()
Cannot set headers after they are sent to the client while using res.redirect()

Time:10-29

So basically i have a route in express. If the user is logged in or they are verified redirect me to the dashboard if i am on the login page else stay where i am in the login page.

function checkGuest(req,res,next) {
  let token = req.cookies['session-token'];
  async function verify() {
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID
    })
  }
  verify()
  .then(() => {
    res.redirect('/dashboard') //if the user is logged in go to dashboard
    next();
  })
  .catch(err => {
    next(); //else stay where you are
  }) 
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

And here's how i am using it in my route:

router.get('/',checkGuest,(req,res) => {
    res.render('login',{
        layout: 'login'
    })
})
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

This is the error Error [ERR_HTTP_HEADERS_SENT] cannot send headers after they are sent back to the client

Hope you understood it.

Your suggestions and quick replies are appreciated

CodePudding user response:

Please return your response. You are not returning the response that's why the header moves to the next line.

function checkGuest(req,res,next) {
  let token = req.cookies['session-token'];
  async function verify() {
    const ticket = await client.verifyIdToken({
      idToken: token,
      audience: CLIENT_ID
    })
  }
  verify()
  .then(() => {
    return res.redirect('/dashboard') //if the user is logged in go to dashboard
  })
  .catch(err => {
    next(); //else stay where you are
  }) 
}
router.get('/',checkGuest,(req,res) => {
    return res.render('login',{
        layout: 'login'
    })
})
  • Related