Reputation: 1073
Is it possible to set up endpoints in Express.js in such a way that the user can signal they'd like only JSON output by appending .json to the URL?
For example, if I have the endpoint example.com/data/:data_id
, is there a function someFunction
such that if I hit the endpoint example.json/data/:data_id
with the following code I would be able to get JSON output out?
router.get('/data/:data_id', function(req, res, next) {
var extension = req.someFunction();
if (extension === 'json') {
res.json({...});
} else {
res.render('view', {...});
};
});
I know there is probably a way to do that with content headers, but I've seen it recommended that content type be specified by an extension so that APIs can be browsed by a browser.
Upvotes: 0
Views: 407
Reputation: 703
I think you could just add a format parameter in the query url
router.get('/data/:data_id', function(req, res, next) {
if (req.query.format && req.query.format === 'json') {
res.json({...});
} else {
res.render('view', {...});
};
});
something like this !
Upvotes: 1