2017-08-29 49 views
1

我正在嘗試設置一個安全檢查中間件,該中間件將在我添加到的路由上運行。使用快遞中間件並將res.local數據傳遞給路由

中間件

function SecurityCheckHelper(req, res, next){ 
    apiKey = req.query.apiKey; 
    security.securityCheck(apiKey).then(function(result) { 
     res.locals.Security = result.securitycheck; 
     console.log(res.locals.Security); 
    }); 
    return next(); // go to routes 

}; 

路線

app.get('/settings', SecurityCheckHelper,function(req, res, next) { 
    console.log(res.locals); 
}); 

其相對簡單的,我試圖通過result.securitycheck(返回真/假)到/settings路線。但是res.locals正在返回一個空對象

+0

這是因爲你的安全檢查是異步的,你立即返回..把下一個在你的..然後.. – Keith

+0

@Keith真棒!你釘在頭上,你能回答這個問題,所以我可以給你信用:D – Charles

回答

1

在您運行安全檢查之前,您的下一個呼叫。

IOW:下一個中間件在安全檢查完成處理之前得到處理。安全檢查是異步的。

將你的下一個放在你的內部,將等待securityCheck完成。

例如。

function SecurityCheckHelper(req, res, next){ 
    apiKey = req.query.apiKey; 
    security.securityCheck(apiKey).then(function(result) { 
     res.locals.Security = result.securitycheck; 
     console.log(res.locals.Security); 
     next(); 
    }); 
}; 
1

您需要將安全檢查承諾與回調接口。

function SecurityCheckHelper(req, res, next){ 
    apiKey = req.query.apiKey; 
    security.securityCheck(apiKey) 
    .then(function(result) { 
     res.locals.Security = result.securitycheck; 
     console.log(res.locals.Security); 
     return next(); 
    }) 
    .catch(err => next(err)); 
}; 
+0

我喜歡增加.catch!謝謝!我把答案給了基思,因爲他先回答了:)雖然謝謝你的幫助! – Charles