Open In App

How to get the full URL in ExpressJS ?

Last Updated : 18 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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);
    }
);


Step 3: Now run the server with the provided command to check whether everything is working fine or not.

node app.js

If yes, then you’ll receive something like this in your terminal, otherwise, In case your server is not starting, analyze the error and check syntax, etc and then restart the server.

Step 4: So now we will continue to create routes and finding the full URL of the request, But let’s first understand the parts of a URL. Below is the description and image which shows the structure of an URL. 

  1. scheme: It is the protocol used to access the resource from the web, it may be HTTP or HTTPS, where ‘s’ stands for security, this scheme can be extracted by the .protocol property of request object like req.protocol.
  2. host: This is the name of the place where all the files required for the server exist in reality. The name of the host can be extracted from the .hostname property from request objects like req.hostname.
  3. port: It is the port number on which the server is listening, this port can be extracted directly in the server because we specify it before starts listening.
  4. path This path determines the actual location of the file, page, resource been accessed, actually, you can think of it as a sub-address it can be extracted by the concatenation of (req.baseUrl + req.path).
  5. query this query is used to provide some data before accessing the resources so that server can respond accordingly, it can be extracted by the req.query property of request objects.

Note: We don’t have to access the baseUrl, path, and query separately express provides us a property called req.originalUrl which contains everything after the hostname.   

The above example URL we are showing will be in your browser’s search bar when you click the algorithm section from the homepage of geeksforgeeks.org

Example: In this example, we are creating a route to receive user requests. We will use the following approach:

  1. In the route provided below, we have specified a function on the ‘*’ path for GET method.
  2. That’s because now we can send any URL from the browser to execute the given functionality.
  3. After then we are simply accessing some properties of the request object,  objectName.propertyName this is one of the ways to extract data.
  4. We have extracted 3 variables as protocol, hostname, and original URL.
  5. In the next line, we are storing the port number which we have set earlier.
  6. Later, We have created a URL string with template literals of ES6, the backticks are the way to create string templates and we can inject any javascript expression inside ${}.
  7. In the end, the function send()  is simply returning the string as a response.

app.js




app.get('*', function (req, res) {    
    const protocol = req.protocol;
    const host = req.hostname;
    const url = req.originalUrl;
    const port = process.env.PORT || PORT;
  
    const fullUrl = `${protocol}://${host}:${port}${url}`
      
    const responseString = `Full URL is: ${fullUrl}`;                       
    res.send(responseString);  
})


Step to run the application: Open the terminal and type the following command.

node app.js

Output:

Explanation:  When we enter any Url in the browser search bar, the browser sends a request object to the server in our case the server is a localhost. And Express catches all user requests at the provided route and inside the functionality of that route. The scheme http extracted from req.protocol, and hostname localhost is extracted from req.hostname and 3000 is being accessed from the PORT which we have set before running the server in step 3, and the remaining URL is being extracted from req.originalUrl.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads