How to get the full URL in Express?
-
The protocol is available as
req.protocol
. docs here- Before express 3.0, the protocol you can assume to be
http
unless you see thatreq.get('X-Forwarded-Protocol')
is set and has the valuehttps
, in which case you know that's your protocol
- Before express 3.0, the protocol you can assume to be
The host comes from
req.get('host')
as Gopal has indicatedHopefully you don't need a non-standard port in your URLs, but if you did need to know it you'd have it in your application state because it's whatever you passed to
app.listen
at server startup time. However, in the case of local development on a non-standard port, Chrome seems to include the port in the host header soreq.get('host')
returnslocalhost:3000
, for example. So at least for the cases of a production site on a standard port and browsing directly to your express app (without reverse proxy), thehost
header seems to do the right thing regarding the port in the URL.The path comes from
req.originalUrl
(thanks @pgrassant). Note this DOES include the query string. docs here on req.url and req.originalUrl. Depending on what you intend to do with the URL,originalUrl
may or may not be the correct value as compared toreq.url
.
Combine those all together to reconstruct the absolute URL.
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
Instead of concatenating the things together on your own, you could instead use the node.js API for URLs and pass URL.format()
the informations from express.
Example:
var url = require('url');
function fullUrl(req) {
return url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: req.originalUrl
});
}
I found it a bit of a PITA to get the requested url. I can't believe there's not an easier way in express. Should just be req.requested_url
But here's how I set it:
var port = req.app.settings.port || cfg.port;
res.locals.requested_url = req.protocol + '://' + req.host + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;
Here is a great way to add a function you can call on the req object to get the url
app.use(function(req, res, next) {
req.getUrl = function() {
return req.protocol + "://" + req.get('host') + req.originalUrl;
}
return next();
});
Now you have a function you can call on demand if you need it.
Using url.format:
var url = require('url');
This support all protocols and include port number. If you don't have a query string in your originalUrl you can use this cleaner solution:
var requrl = url.format({
protocol: req.protocol,
host: req.get('host'),
pathname: req.originalUrl,
});
If you have a query string:
var urlobj = url.parse(req.originalUrl);
urlobj.protocol = req.protocol;
urlobj.host = req.get('host');
var requrl = url.format(urlobj);