如何使用express从不同的中间件中获取响应对象的数据

时间:2016-03-15 06:50:22

标签: node.js express swagger swagger-ui

可能是这个愚蠢的问题.. :)可以帮助我从响应对象中获取数据。基本上我想使用express

中的其他middlware来验证我的响应数据
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/', function(req, res, next){
    console.log('entry point');
    res.json({name:"somename",age: 29});
    next()
});

var middleware = function (req, res, next) {

console.log('LOGGED');

res.end = function (req, res , next) {
    var data = res.data;
    //do some validation logic here
    next()
}};
app.use(middleware);

var port = process.env.PORT || 10010;
app.listen(port);

1 个答案:

答案 0 :(得分:0)

在中间件函数中,没有调用 res.end 函数,也没有在中间件中调用 next 函数。做这样的事情:

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

app.use('/', function(req, res, next){
    console.log('entry point');
    res.json({name:"somename",age: 29});
    next()
});

var middleware = function (req, res, next) {

  console.log('LOGGED');

  res.end = function (req, res , next) {
    var data = res.data;
    //do some validation logic here
    next()
  };
  next();
};
app.use(middleware);

app.use((req, res) => res.end()); // here your end function will be called

var port = process.env.PORT || 10010;
app.listen(port);