Monday 8 May 2017

Redirect and Render using Express

When I hit my api I want to redirect my url from https://myapp.herokuapp.com/token/aaa.bbb.ccc to https://myapp.herokuapp.com/messages/:id. I also want to render my message view

Code:

app.get('/token/:id' , (req, res) => {
  var decoded = jwt.verify(req.params.id, 'blabla');
  Message.findById(decoded.messageId, (err, message) => {
    if (err) res.json({error: err})
    res.render('message', {message})
  })
})

Here, I successfully render my message view but the URL for the below api is still https://myapp.herokuapp.com/token/aaa.bbb.ccc and not https://myapp.herokuapp.com/messages/:id

Another attempt:

app.get('/token/:id' , (req, res) => {
  var decoded = jwt.verify(req.params.id, 'blabla');

  Message.findById(decoded.messageId, (err, message) => {
    if (err) res.json({error: err})
    res.redirect('/messages/'+message._id)
  })
})

Now, the URL is https://myapp.herokuapp.com/messages/:id but the message view is not rendered. A JSON is rendered that displays the message

How do I redirect to https://myapp.herokuapp.com/messages/:id and also render the message view?



via user2456977

No comments:

Post a Comment