How to get the Full URL in Express on Node.js
📣 Sponsor
In Express running on Node.js, we have access to the request
object, and also we can send a response back to the user via the response
object. However, we don’t have access to a simple way of getting the full URL from the request
.
Fortunately, it is quite easy to build the full URL from the request
object in Express. Let’s look at how it works.
Getting the full URL of a Request in Express
In express, we can display certain content on certain routes like so:
app.get('/page', (req, res, next) => {
// Show some content to the user
})
Within a route, we can use the req
object to get the full URL. The full URL is composed of a few different pieces:
- the protocol of the current URL
- the host of the URL (i.e. the domain name)
- and the page you are on, i.e.
/page
To combine all of these from our request, we can run the following:
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
Note: it is better to use req.get('host')
, since it will include the port. So if you’re running on localhost:3000
, then :3000
will be included. req.hostname
only returns the domain, or localhost
- which may cause issues for you in the future.
Therefore, a full URL can be found for any page our route, using the following code:
app.get('/page', (req, res, next) => {
// Show some content to the user
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
})
More Tips and Tricks for Javascript
- How to get the last element of an Array in Javascript
- How to Stop Using jQuery
- Web Workers Tutorial: Learn how Javascript Web Workers Work
- Inserting an Item into an Array at a Specific Index in Javascript
- How to install nvm, the Node Version Manager
- Javascript Logical Statements and Loops
- Asynchronous Operations in Javascript
- Javascript ShadowRealms
- A Guide to Heaps, Stacks, References and Values in Javascript
- Resolving HTTP Cannot set headers after they are sent to the client in Node.JS