Reputation: 2680
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?
Upvotes: 3
Views: 1154
Reputation: 9136
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
Upvotes: 3
Reputation: 5848
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);
Upvotes: 1