Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Does anybody know a way in express.js to capture requests in a single function for both html and json?

Essentially I want a single route for both /users and /users.json - like rails does with its routes -> controller.

That way, I can encapsulate the logic in a single function and decide to render either html or json.

Something like:

app.get('/users[.json]', function(req, res, next, json){
  if (json)
    res.send(JSON.stringfy(...));
  else
    res.render(...); //jade template
});

Could I use a param perhaps?

like image 895
justinjmoses Avatar asked Sep 11 '25 07:09

justinjmoses


2 Answers

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();
});
like image 117
Beau Avatar answered Sep 12 '25 22:09

Beau


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

like image 26
alessioalex Avatar answered Sep 12 '25 22:09

alessioalex