1

I am porting over a DJANGO API to Node.js and have a requirement to support .json at the end of a route.

Example: a GET to /users/:id/.json would return the JSON object representing the user.

The problem is that I have some routes with custom behavior, so I need it to return the same logic I would run as if I did a GET to /users/:id.

I can easily duplicate the original route and add /.json to it, but that is not the way I'd like to do it for obvious reasons.

What approach could I use to 'automatically' tack a .json handler to the end of a route, and have it instead use a different custom route?

mcheshier
  • 715
  • 4
  • 13
  • Can't you make it an optional route parameter and do the logic check (whether or not use the custom behavior) in your controller? – stUrb Jan 22 '16 at 19:11
  • What if you add a query param? `?type=json` – Josh Beam Jan 22 '16 at 19:12
  • add a middleware that looks for .json before your router, and if found sets a property on req and removes it from the url, allowing your routes to handle it as usual. But probably better to just use a proper header or query parameter. – Kevin B Jan 22 '16 at 19:18
  • To follow-up on @stUrb comment, see this question: http://stackoverflow.com/questions/10020099/express-js-routing-optional-spat-param – user949300 Jan 22 '16 at 19:53
  • I had no idea you could use * in routes like that, it should meet my needs. Post that as an answer and I will accept it. – mcheshier Jan 27 '16 at 22:08

1 Answers1

0

A good way to do that is with query parameters. You can define your route as you normally would:

/users/:id

And then have some logic (say, in a middleware) that looks for the type query parameter.

if(req.query.type) {
  if(req.query.type === 'json') {
    // send json
  }
}

The full route that the client would hit would then be: /users/12345?type=json

Reference: express docs, req.query section

Josh Beam
  • 19,292
  • 3
  • 45
  • 68