Simon Guldstrand
Simon Guldstrand

Reputation: 488

What is the simplest and/or best way to send data between routes in node.js express?

My setup is like this:

I get data from omDB using a omdb lib from github, this whole parts looks like this:

router.post('/search', function(req, res) {

    var omdb = require('omdb');

    var title = req.body.title;

    omdb.get( {title: title}, true, function(err, movie){
        if(err) {
            return console.log(err);
        }

        if(!movie) {
            return console.log('No movie found');
        }

        //console.log('%s (%d)', movie.title, movie.year);

        result = movie.title+movie.year+movie.poster;

        console.log(result);

        res.redirect('/result');
    })


});

And then i want to use the result from that post request in another route:

router.get('/result', function(req, res) {

    res.render('result', { title: title});

});

What is the best and hopefully simplest approach to do this, consider that I am a node.js noob.. :)

Upvotes: 0

Views: 3456

Answers (1)

soulprovidr
soulprovidr

Reputation: 754

Assuming you're using express.js, you could use the session middleware:

router.post('/search', function(req, res) {

    var omdb = require('omdb');

    var title = req.body.title;

    omdb.get( {title: title}, true, function(err, movie){
        if(err) {
            return console.log(err);
        }

        if(!movie) {
            return console.log('No movie found');
        }

        //console.log('%s (%d)', movie.title, movie.year);

        req.session.result = {
            title: movie.title,
            year: movie.year,
            poster: movie.poster
        };

        res.redirect('/result');
    })


});

then:

router.get('/result', function(req, res) {

    if (req.session.result) {

        var result = req.session.result;
        req.session.result = null;
        res.render('result', { movie: result });

    }
    else {

        // Redirect to error page.

    }
});

Upvotes: 2

Related Questions