I want to get the url the client has requested out of the request.
Currently I use:
var requestedUrl = req.protocol + '://' + req.host + ':3000' + req.url;
This isn't really nice at all. It also leaves out url fragments I require (#/something).
Is there a way I can get the complete url? Maybe out of the header?
Regards
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
You cannot get the fragment (hash section) of a url on the server, it does not get transmitted by the browser.
The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the server — of course the server typically helps to determine the MIME type, and the MIME type determines the processing of fragments. When an agent (such as a Web browser) requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent processes the resource according to the document type and fragment value.
From Fragment Identifier on Wikipedia
If you want to get the complete URL (without the fragement identifier), the best way would be to use the "Host" header which includes the port rather than req.host but otherwise the same as you are currently doing:
var requestedUrl = req.protocol + '://' + req.get('Host') + req.url;
I often times add something like this to my express app:
app.use(function(req, res, next) {
req.getRoot = function() {
return req.protocol + "://" + req.get('host');
}
return next();
});
Now you have a function you can call on demand if you need it.
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