2017-04-17 41 views
-1

我有一個POST方法,調用next()函數,但是當我嘗試訪問res屬性時,我得到undefined。如果我打印:req屬性爲空Express

console.log(res) 

我可以看到我需要的屬性,但由於某種原因,嘗試訪問它們返回undefined。 這是我的代碼:

app.post('/login', [function(req, res, next){ 

req.ID = "hello, world" 
next(); 

}, function(req, res){ 

    console.log(res) //I can see res.ID I am trying to access in the log 
    console.log(res.ID) //undefined 
}) 

我:

app.use(bodyParser.urlencoded({ extended: true })); 
app.use(bodyParser.json()); 

在我的文件的最頂端。

回答

0

根據您提供的代碼,您在沒有關閉已定義登錄中間件的陣列時出現語法錯誤。

爲了提高可讀性和模塊性,我建議將中間件移至某個函數,然後將函數引用傳遞給Express路由定義。

function loginMiddleware (req, res, next) { 
    req.ID = 'Hello World' 

    return next() 
} 

app.post('/login', loginMiddleware, (req, res) => { 
    console.log(req.ID) // logs 'Hello World' 
})