Node.js Express, router, optimal parameter as an extension

First Node.js Express app. In routes, I have a route named / info that renders the info page template.

app.js:

app.use('/info', info);

      

info.js:

// routes to /info, and should also handle /info.json
router.get('/', function(req, res) { //... });

      

I also want to use the same function above to use the optimal .json parameter to display json content instead - /info.json .

I'm trying with regex, but I can't seem to get it to work. I can only do: /info/.json

Can this be done using the same function?

+3


source to share


2 answers


I would use the content-negotiation function of express. First, declare your route like this:

app.get('/info(.json)?', info);

      

Then in the info (taken from the link above):



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

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

      

EDIT : Using one route with regex

+3


source


With, app.use('/info', info);

you tell the route info

. This is why you get /info/.json

, so you will have a change in how you have everything you need to work.

Instead, module.exports = router;

in your info.js file, you need to do something like this:

module.exports = function(req, res) {
   if(req.isJSON) {

   } else {

   }
}

      



In your app.js application you will have some route middleware to mark the request as .json

:

app.use('*.json', function() {
  req.isJSON = true;
  next();
});

app.get('/info', info);
app.get('/info.json', info);

      

+1


source







All Articles