听起来您正在寻找使用相同代码处理两条路线。如果您不想使用 301 重定向res.redirect
,请考虑组织您的代码,以便分离共享逻辑并为两条路由执行它。req.session
即使它不发送重定向,您仍然可以使用内部处理函数链来维护变量范围。或者,您可以使用回调将复杂代码放置在其自己的函数中并按需执行。
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, /') });
// strategy 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);
});
// strategy 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');
});