node.js - express single route, multiple functions -


is there way have multiple functions against single route.

app.get('/r1', function(req, res) {   res.send('hello world 1'); });  app.get('/r1', function(req, res) {   res.send('hello world 2'); }); 

reason: content negotiation, https://en.wikipedia.org/wiki/content_negotiation i've different modules based on accept header in different scopes, can't reach out 1 other in router.

please advise.

while can't have multiple functions per routes first described, can content negotiation inside route,

look @ req.is(type) http://expressjs.com/api.html

something along lines of

app.get('/r1', function(req, res) {   if(req.is('html')) {     //do html stuff     return res.send('it html')   }    if(req.is('json')) {     //do json stuff     return res.send('it json')   }      //wasn't html or json, send 406     res.status(406);     res.send('content type not acceptable'); }); 

alternatively, has made handy little npm package above: https://www.npmjs.com/package/express-negotiate

edit

as per comment, res.format can used on accept header: please see previous link

app.get('/r1', function(req, res) {    res.format({     'text/plain': function(){       res.send('hey');     },      'text/html': function(){       res.send('<p>hey</p>');     },      'application/json': function(){       res.send({ message: 'hey' });     },      'default': function() {       // log request , respond 406       res.status(406).send('not acceptable');     }   }); }); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -