Let's say my sample URL is
http://example.com/one/two
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
.
To get the full URL in Express and Node. js, we can use the url package. to define the fullUrl function that takes the Express request req object. And then we call url.
json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.
The protocol is available as req.protocol
. docs here
http
unless you see that req.get('X-Forwarded-Protocol')
is set and has the value https
, in which case you know that's your protocolThe 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 so req.get('host')
returns localhost: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), the host
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 to req.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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With