如何制作中间件以响应所有ajax请求

如何制作中间件以响应所有ajax请求,ajax,node.js,express,routes,Ajax,Node.js,Express,Routes,我需要制作一个中间件来处理对web用户的每个响应。我试着做如下的事情: 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 somet

我需要制作一个中间件来处理对web用户的每个响应。我试着做如下的事情:

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响应添加一些默认状态

在上述方法中,我不喜欢的一件事是在每个路由中添加AjaxResponseMiddware函数


那么,您对这种方法有何看法?您可以提出改进建议或分享您的经验。

中间件只是一个函数
函数(req、res、next){}

var express = require('express');
var app = express();

// this is the middleware, you can separate to new js file if you want
function jsonMiddleware(req, res, next) {
    res.json_v2 = function (code, data) {
        if(!data) {
            data = code;
            code = 200;
        }
        // place your modification code here
        //
        //
        res.json(code, data)
    }
    next();
}

app.use(jsonMiddleware); // Note: this should above app.use(app.router)
app.use(app.router);

app.get('/ajax1', function (req, res) {
    res.json_v2({
        name: 'ajax1'
    })
});

app.listen(3000);

但当我像if(err){return next(err)}这样处理错误时,它将如何工作呢?当调用中间件时,这意味着之前没有错误发生。如果jsonMiddleware内部发生错误,只需调用returnNext(err)Ok。非常感谢您的回答,但最好将json_v2函数添加到局部变量中,而不是res object?局部变量用于将参数从控制器发送到视图(像jade或ejs一样渲染),因此如果您在渲染中不调用该函数,则不应将其指定给局部变量。如我所见,您在控制器中调用该函数。我只是害怕重写res对象的任何方法