× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How do I redirect in expressjs while passing some context?

James Qualls
Jun 28, 2015
<p>The easiest way I have found to pass data between routeHandlers to use <code>next()</code> no need to mess with redirect or sessions. Optionally you could just call your <code>homeCtrl(req,res)</code> instead of <code>next()</code> and just pass the <code>req</code> and <code>res</code></p> <pre><code>var express = require('express'); var jade = require('jade'); var http = require("http"); var app = express(); var server = http.createServer(app); ///////////// // Routing // ///////////// // Move route middleware into named // functions function homeCtrl(req, res) { // Prepare the context var context = req.dataProcessed; res.render('home.jade', context); } function categoryCtrl(req, res, next) { // Process the data received in req.body // instead of res.redirect('/'); req.dataProcessed = somethingYouDid; return next(); // optionally - Same effect // accept no need to define homeCtrl // as the last piece of middleware // return homeCtrl(req, res, next); } app.get('/', homeCtrl); app.post('/category', categoryCtrl, homeCtrl); </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/19035373/How%20do%20I%20redirect%20in%20expressjs%20while%20passing%20some%20context?/24513573">Stack Overflow</a>.</p>
comments powered by Disqus