how to get data from response object in different middleware using express

Viewed 2101

May be this silly question .. :) can some will help me to get the data from response object . Basically I want to validated my response data using other middlware in express

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 Answers

In the middleware function, neither res.end function is getting called, nor next function is getting called in your middleware. Do something like this:

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