req属性为null Express

时间:2017-04-17 17:57:51

标签: node.js express

我有一个调用next()函数的POST方法但是当我尝试访问res属性时,我得到undefined。如果我打印:

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

位于我文件的最顶层。

1 个答案:

答案 0 :(得分: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'
})
相关问题