Issue
Let’s say my sample URL is
and I say I have the following route
app.get('/one/two', function (req, res) {
var url = req.url;
}
The value of url
will be /one/two
.
How do I get the full URL in Express?
For example, in the case above, I would like to receive http://example.com/one/two
.
Solution
-
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 indicated -
Hopefully 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;