2014-01-25 10 views
0

這是新的中間件失敗

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(); 
}); 

我想設置的函數,在這樣answer

響應對象,我得到這個錯誤

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

爲什麼我的代碼不工作?

+0

你在哪裏試圖使用'res.errorFromServer()'?這個中間件是在'app.use(app.router)'還是第一個路由('app.get()')之前'使用'的? –

+0

在app.use之後使用(app.router – andrescabana86

+0

順序對中間件有影響。如果'app.router'是第一個,那麼'errorFromServer'將不會被定義爲你的任何路由。 –

回答

0

您代碼中的主要問題是,您使用了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(); 
});