【发布时间】:2013-12-29 00:39:16
【问题描述】:
我需要制作一个中间件来处理对网络用户的每个响应。我尝试制作如下内容:
function ajaxResponseMiddleware(req, res, next) {
var code = res.locals._code || 200;
var data = res.locals._response;
res.json(code, data);
}
app.get('/ajax1', function(req, res, next){
// Do something and add data to be responsed
res.locals._response = {test: "data2"};
// Go to the next middleware
next();
}, ajaxResponseMiddleware);
app.get('/ajax2', function(req, res, next){
// Do something and add data to be responsed
res.locals._response = {test: "data2"};
res.locals._code = 200;
// Go to the next middleware
next();
}, ajaxResponseMiddleware);
响应在 ajaxResponseMiddleware 函数中处理,我可以在其中为所有 ajax 响应添加一些默认状态。
我不喜欢上述方法的一件事是在每个路由中添加 ajaxResponseMiddleware 函数。
那么您如何看待这种方法?请您提出改进建议或分享您的经验。
【问题讨论】:
标签: ajax node.js express routes