Skip to content
Advertisement

Overwrite response status of endpoint in expressjs

I managed to redirect root '/' to '/users' but '/users' endpoint status overwrites the root endpoint status.

app.get('/', (req, res) => {
  res.redirect(301, '/users');
});
    
app.get('/users', (req, res) => {
  res.status(200).json(data.filter(user => user.isActive === true));
});

How is it possible to check whether '/users' endpoint is accessed through redirect or not and then set res.status appropriately?

Advertisement

Answer

I am not sure why you want root api http status to be send in response of /users api but below hack can be applied to recognise if request are received from root api.

app.get('/', (req, res) => {
  res.redirect(301, '/users?redirect=true');
});
    
app.get('/users', (req, res) => {
  const redirect = req.query.redirect;
  if (redirect) {
    res.status(301).json(data.filter(user => user.isActive === true));
  } else {
    res.status(200).json(data.filter(user => user.isActive === true));
  }
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement