It appears that you are seeking to handle two routes using the same code. If you prefer not to employ a 301 redirect with res.redirect
, consider restructuring your code so that you can segregate the shared logic and execute it for both routes. You can still utilize req.session
to maintain variable scope within an internal handler function chain, even if no redirect is being sent. Alternatively, you could encapsulate the intricate code in its own function with a callback and invoke it as needed.
var http = require('http')
var express = require('express');
var app = module.exports = express();
app.use(express.logger('dev'));
app.use(express.cookieParser('asdf 0a98234ja af anekjoavzcx'));
app.use(express.session());
app.use(app.router);
app.get('/', function(req, res){ res.send(200, 'Hi, /') });
// Approach 1
function complexThings1(req, res, next){
console.log('#complex stuff started')
process.nextTick(function(){ // example asynchronous function
req.session.complexOutput="2i+3";
console.log('#complex stuff finished')
next();
});
};
app.get('/myverylongurl', complexThings1, function(req, res){
res.send(200, 'complex things 1 output: '+req.session.complexOutput);
});
app.get("/r/*", complexThings1, function(req, res){
res.send(200, 'complex things 1 output: '+req.session.complexOutput);
});
// Approach 2
function complexThings2(input, callback){
console.log('#complex stuff finished');
process.nextTick(function(){ // example asynchronous function
console.log('#complex stuff finished');
var output = input
callback(null, output);
});
};
app.get('/s/*', function(req, res){
complexThings2('8i+3.14', function(err, output){
res.send(200, 'complex things 2 output: '+output);
});
});
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
http.createServer(app).listen(3000, function(){
console.log('Express server listening on port 3000');
});