In 2022
The above answers are working fine but are not preferred by the Documentation because url.parse
is now legacy
so I suggest you to use new URL()
function if you want to get more control over url
.
Express Way
You can get Full URL
from the below code.
`${req.protocol}://${req.get('host')}${req.originalUrl}`
Example URL: http://localhost:5000/a/b/c?d=true&e=true#f=false
Fixed Properties ( you will get the same results in all routes )
req.protocol: http
req.hostname: localhost
req.get('Host'): localhost:5000
req.originalUrl: /a/b/c?d=true&e=true
req.query: { d: 'true', e: 'true' }
Not Fixed Properties ( will change in every route because it controlled by express itself )
Route: /
req.baseUrl: <blank>
req.url: /a/b/c?d=true&e=true
req.path: /a/b/c
Route /a
req.baseUrl: /a
req.url: /b/c?d=true&e=true
req.path: /b/c
Documentation: http://expressjs.com/en/api.html#req.baseUrl
URL Package Way
In the URL
function, you will get the same results in every route so properties are always fixed.
Properties
const url = new URL(`${req.protocol}://${req.get('host')}${req.originalUrl}`);
console.log(url)
You will get the results like the below. I changed the order of the properties as per the image so it can match the image flow.
URL {
href: 'http://localhost:5000/a/b/c?d=true&e=true',
protocol: 'http:',
username: '',
password: '',
hostname: 'localhost',
port: '5000',
host: 'localhost:5000',
origin: 'http://localhost:5000',
pathname: '/a/b/c',
search: '?d=true&e=true',
searchParams: URLSearchParams { 'd' => 'true', 'e' => 'true' },
hash: ''
}
Note: Hash
can not send to the server because it treats as Fragment
in the server but you will get that in the client-side means browser.
Documentation: https://nodejs.org/api/url.html#url_new_url_input_base
req.completeURL()
method · Issue #4697 · expressjs/express for this. – Fructification