在express.js,任何方式来捕获请求到一个函数json和html?

有没有人知道在express.js的方式来捕获请求在一个单一的function为HTML和JSON?

基本上我想为/users/users.json使用单一路由 – 就像使用rails的路由 – > controller一样。

这样,我可以封装逻辑在一个单一的function,并决定呈现HTML或JSON。

就像是:

 app.get('/users[.json]', function(req, res, next, json){ if (json) res.send(JSON.stringfy(...)); else res.render(...); //jade template }); 

我可以使用一个参数吗?

一个路由是一个简单的string,它被编译到一个RegExp内部,如手册所说,所以你可以做这样的事情:

 app.get("/users/:format?", function(req, res, next){ if (req.params.format) { res.json(...); } else { res.render(...); //jade template } }); 

点击此处查看: http : //expressjs.com/guide.html#routing

我相信res.format()是在Express 3.x和4.x中执行此操作的方法:

 res.format({ text: function(){ res.send('hey'); }, html: function(){ res.send('<strong>hey</strong>'); }, json: function(){ res.send({ message: 'hey' }); } }); 

这依赖于Accept头,但是你可以使用自定义中间件或类似connect-acceptoverride的东西来自定义这个头。

自定义中间件的一个例子可能是:

 app.use(function (req, res, next) { var format = req.param('format'); if (format) { req.headers.accept = 'application/' + format; } next(); }); 

我对上述答案不满意。 这是我所做的。 如果它能帮助你,请投票。

我只是确保所有的json请求都将Content-Type头设置为“application / json”。

 if (req.header('Content-Type') == 'application/json') { return res.json({ users: users }); } else { return res.render('users-index', { users: users }); }