Hướng dẫn nodejs get full url

In 2021

The above answers are working fine but 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 on 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: 
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

Hướng dẫn nodejs get full url

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

URL stands for Uniform Resource Locator. It is used to locate some resources on the internet it can be thought of as a web address. The string you type on your browser search bar to get something from the internet is a URL, so in this process, the browser somehow finds the address of the server associated with that web address and says hey, this is the content(an URL) I have got from the user and now tell me how I should respond. Now it is the server’s responsibility to respond according to that request. And after receiving a response, it’s the browser’s responsibility to provide that received data to a user in the way it is expected.

Problem statement: So that was pretty much about URL, now our problem statement is how to get that URL at the server? Because during the application in production, several times we need the Whole components of URL to understand the user requirements so that later server can fulfill them by sending a proper response.  

Approach: There is an easy and simple approach to solve this because directly or indirectly the user sends the request object and it contains sufficient information for the server. And we can extract essential properties from that object according to our needs. In this article, at step number 4, we are going to discuss how to construct the URL from this request object sent by the user.

Step 1: Creating nodejs project and installing packages.

1. Create a nodejs application. As the whole operation is going to proceed with express framework hence it is the first compulsory step to create a node application.

npm init

2. This will ask you for few configurations about your project you can fill them accordingly, also you can change it later from the package.json file, you can use `npm init -y` for default initialization.

Install express framework

npm install express

3. Create a new file app.js, inside this file, we will write the whole express code. 

Project Structure: It will look like the following.

Hướng dẫn nodejs get full url

Step 2: Creating an express application. So inside app.js do the following:

  1. Import express with require keyword and,
  2. Then call the express() function provided by the express framework.
  3. That function call will return our created app, store it in a const variable.
  4. Set a PORT for your application 3000 is default but you can choose any other according to availability.
  5. After then, call the listen() function, and with this our express server starts listening to the connection on the specified path.
  6. The listen function takes port and callback function as an argument.

The callback function provided as an argument gets executed either on the successful start of the server or it provides an error due to failure.

app.js


const express = require('express'); // Import
const app = express();              // Create
const PORT = 3000;                  // Configure

// Do your task here, in this space.

app.listen(PORT, (error) => {       // Listen
    if(!error)
        console.log("Server is Successfully Running,
            and App is listening on port "+ PORT)
    else
        console.log("Error occurred, server can't start", error);
    }
);