简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM