Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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?

Problem courtesy of: justinjmoses

Solution

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

Solution courtesy of: alessioalex

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×