简体   繁体   中英

Node.js Express How to pass data between middleware?

I am trying to send data in MEAN Stack in Node/Express from one middleware to another, I have a route set up, where I have 2 named functions, one queries some data and passes it to a second function that should do some other processing on the data... here is my routing function that has the 2 middleware functions on the "get" method:

function DemonstratorRoutes(router) {
    var DemonstratorController = require('../controllers/DemonstratorController')
    router.route('/Demonstrator')
      .get(DemonstratorController.list_all_Demonstrator, DemonstratorController.doSomeStuff)
module.exports = DemonstratorRoutes;

the implementation of the functions are as follows, its just simple stuff for demonstration / try out purpose..:

exports.list_all_Demonstrator = function(req, res,next) {
    //console.log(req.body)
    Demonstrator.find({},  function(err, demo) {
        if (err){
            console.log(err);}
        else {
            res.locals.myvar = demo;    
        }
    });
    next();
};

exports.doSomeStuff = function(req,res,next) {
    var data;
    data = res.locals.myvar
    console.log("Dies ist 2te Funktion:", data);
    res.send(data);
}

I have seen that example somewhere... however they did implement it otherwise, they just defined anonymous functions one after the other, separated by commas, but I would like to use named functions and use them in the route file as parameters for Express routing function middleware.. However, I have the problem that the data in the second function is "undefined", I dont understand why this does not work, has it to do with function hoisting? Maybe I have to define my functions otherwise? Or is my callback wrong?

Demonstrator.find is an asynchronous function, so you should call next in its callback like this

exports.list_all_Demonstrator = function(req, res,next) {
//console.log(req.body)
Demonstrator.find({},  function(err, demo) {
    if (err){
        console.log(err);
    }
    else {
        res.locals.myvar = demo;    
    }
    next(); // <------------
});

};

exports.doSomeStuff = function(req,res,next) {
    var data;
    data = res.locals.myvar
    console.log("Dies ist 2te Funktion:", data);
    res.send(data);
}

Otherwise next will be called before you assign demo to res.locals.myvar

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