简体   繁体   中英

Node.js Express, router, optimal param as extension

My first Node.js Express app. In the routes, I'm having a route called /info , which renders an 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 be able to use the same function above, to use an optimal parameter .json , to render json content instead - /info.json .

I've been trying with regex but I can't get it to work. I can only manage to do: /info/.json

Is it possible to do this using the same function?

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

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

Then in info (taken from link above):

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

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

EDIT : using a single route with regex

With using app.use('/info', info); you're saying route the info path. That's why you're getting /info/.json so you're going to have change how you have things set up for this to work.

Instead of module.exports = router; in your info.js, you'll want to do something like this:

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

   } else {

   }
}

In your app.js you'll have some route middleware to flag the request as .json :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM