What is the simplest and/or best way to send data between routes in node.js express? -
my setup this:
i data omdb using omdb lib github, whole parts looks 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 want use result post request in route:
router.get('/result', function(req, res) { res.render('result', { title: title}); });
what best , simplest approach this, consider node.js noob.. :)
assuming you're using express.js, use 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 error page. } });
Comments
Post a Comment