in express.js, any way to capture request to both json and html in one function?

房东的猫 提交于 2019-11-29 21:30:28

A route is simple a string which is compiled to a RegExp internally, as the manual says, so you can do something like this:

app.get("/users/:format?", function(req, res, next){
  if (req.params.format) { res.json(...); }
  else {
    res.render(...); //jade template
  }
});

Check more here: http://expressjs.com/guide.html#routing

I believe res.format() is the way to do this in Express 3.x and 4.x:

res.format({
  text: function(){
    res.send('hey');
  },

  html: function(){
    res.send('<strong>hey</strong>');
  },

  json: function(){
    res.send({ message: 'hey' });
  }
});

This relies on the Accept header, however you can munge this header yourself using a custom middleware or something like connect-acceptoverride.

One example of a custom middleware might be:

app.use(function (req, res, next) {
  var format = req.param('format');

  if (format) {
    req.headers.accept = 'application/' + format;
  }

  next();
});

I was not happy with the above answers. Here's what I did instead. Please vote up if it helps you.

I just make sure that all json requests have the Content-Type header set to 'application/json'.

if (req.header('Content-Type') == 'application/json') {
  return res.json({ users: users });
} else {
  return res.render('users-index', { users: users });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!