node.js - 如何在 express.js 中获得完整url?

假设我的例子网址是: http://example.com/one/two


app.get('/one/two', function (req, res) {
 var url = req.url;
}

"url"的值为"/one/two"

如何获得完整的url值?

时间:


 var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;

应该是req.requested_url


var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host + ( port == 80 || po
rt == 443 ? '' : ':'+port ) + req.path;

自己,而不是连接在一起的事情,你可以使用url node.js api,通过 URL.format() 表达的信息。


 app.use(function(req, res, next) {
 req.getUrl = function() {
 return req.protocol +"://" + req.get('host') + req.originalUrl;
 }
 return next();
 });

我建议使用originalUrl代替URL :


var url = req.protocol + '://' + req.get('host') + req.originalUrl;

在这里查看originalUrl的描述: http://expressjs.com/api.html#req.originalUrl


 foo = express();
 express().use('/foo', foo);
 foo.use(require('/foo/blah_controller'));

blah_controller看起来像这样:


 controller = express();
 module.exports = controller;
 controller.get('/bar/:barparam', function(req, res) { /* handler code */ });

URL有以下格式:


www.example.com/foo/bar/:barparam

...