user2456977
user2456977

Reputation: 3964

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?

Upvotes: 1

Views: 2462

Answers (1)

robertklep
robertklep

Reputation: 203251

You should first redirect:

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

  Message.findById(decoded.messageId, (err, message) => {
    if (err) return res.json({error: err}); // see @partycoder's answer
    res.redirect('/messages/'+message._id)
  })
})

Next, you need to adjust the route handler for /messages/:id. Right now, it sounds like it's only used for XHR requests, so it will always return JSON. You can add a check to see if the request is an XHR-request or not, and either return JSON (for XHR) or a rendered template (for non-XHR):

app.get('/messages/:id', (req, res) => {
  ...
  if (req.xhr) {
    return res.json(...);
  } else {
    return res.render(...);
  }
});

(documentation for req.xhr, be aware that the method on which this is based is not foolproof)

However, perhaps it's better to use content negotiation, where the client explicitly tells your server what format the response should be. The upside of this is that it's much more explicit, the downside is that you may have to change some client-side code. Documentation here: http://expressjs.com/en/4x/api.html#res.format

Upvotes: 3

Related Questions