我的第一个Node.js Express应用程序。在路由中,我有一个名为/ info的路由,该路由呈现一个信息页面模板。
app.js:
app.use('/info', info);
info.js:
// routes to /info, and should also handle /info.json
router.get('/', function(req, res) { //... });
我也希望能够用上述同样的功能,以便使用最佳参数以.json,呈现JSON而不是内容- /info.json。
我一直在尝试使用正则表达式,但无法正常工作。我只能设法做到:/info/.json
是否可以使用相同的功能来执行此操作?
我会使用express的内容协商功能。首先,声明您的路线,例如:
app.get('/info(.json)?', info);
然后在信息中(取自上面的链接):
res.format({
'text/html': function(){
res.send('hey');
},
'application/json': function(){
res.send({ message: 'hey' });
}
});
编辑:与正则表达式一起使用单个路由
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句