2017-04-17 59 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' 
})