繁体   English   中英

Express 3中的新中间件失败

[英]new middleware in express 3 fails

这是中间件

app.use(function (req, res, next){

    res.locals.appdata      = appdata;
    res.locals.errorMessage = "";
    res.locals.information  = {};
    res.errorFromServer     = function (req, res){

        var mensaje = res.locals.errorMessage;

        res.status(500);
        res.locals.errorMessage = "";

        return res.render('error/500',{errorMessage: mensaje || ""});
    }

    next();
});

我正在尝试像这样的答案在响应对象中设置功能

我收到这个错误

TypeError: Object #<ServerResponse> has no method 'errorFromServer'

为什么我的代码无法正常工作?

代码中的主要问题是,您使用了res对象,并使用return res.render(..)返回了响应。 之后, next()的用途是什么?

最重要的是,您要向res对象添加一个函数(而不是值)(您引用的答案使用req对象并称为函数,它返回了一个值并将其分配给req对象)。

//Example
function getBrowser() {
    return this.get('User-Agent'); //This returns the value.
}

app.use(function (req, res, next) {
  req.getBrowser = getBrowser; // You are assigning a value not a function itself.
  next();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM