【问题标题】:How to make middleware for response on all ajax requests如何制作中间件以响应所有 ajax 请求
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 但是当我处理 if (err) { return next(err) } 之类的错误时它将如何工作?
    • 当一个中间件被调用时,这意味着之前没有发生错误。如果 jsonMiddleware 内部发生错误,只需调用 return next(err)
    • 好的。非常感谢您的回答,但也许更好地将 json_v2 函数添加到本地而不是 res 对象中?
    • locals 用于将参数从控制器发送到视图(像jade 或ejs 一样渲染),因此如果您不在渲染中调用该函数,则不应分配给本地人。如我所见,您在控制器中调用该函数。
    • 我只是害怕覆盖 res 对象的任何方法
    猜你喜欢
    • 2020-08-06
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 2012-02-24
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    相关资源
    最近更新 更多