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

时间:2013-12-11 06:48:24

标签: 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 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功能。

那你怎么看待这种方法呢?您可以建议改进或分享您的经验。

1 个答案:

答案 0 :(得分:5)

中间件只是一个函数function (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);