Open In App

How to get full URL in Express.js ?

Last Updated : 17 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Express is a small framework that sits on top of Node.js’s web server functionality to simplify its APIs and add helpful new features. It makes it easier to organize your application’s functionality with middleware and routing. It adds helpful utilities to Node.js’s HTTP object and it facilitates the rendering of dynamic HTTP objects.

Use the following steps to install the module and get the full URL in Express.js:

Step 1: Creating a directory for our project and making that our working directory.

$ mkdir demo
$ cd demo

Step 2: Use the npm init command to create a package.json file for our project.

$ npm init

Note: Keep pressing enter and enter “yes/no” accordingly at the terminus line.

Step 3: Installing the Express.js module. Now in your demo(name of your folder) folder type the following command line:

$ npm install express --save

Step 4: Creating index.js file, our Project structure will look like this.

Step 5: Creating a basic server. Write down the following code in the index.js file.

index.js




const express = require('express');
const app = express();
  
app.get('/' , (req , res)=>{
    res.send("GeeksforGeeks");
})
  
// Server setup
app.listen(4000 , ()=>{
    console.log("server is running on port 4000");
})


Output: We will get the following output in the browser screen.

GeeksforGeeks

Step 6: Getting the full link as a response to a request. Here, For the full link, we are going to use protocol, hostname, and original URL which is present in the request object.

index.js




const express = require('express');
const app = express();
  
  
app.get('/' , (req , res)=>{
    res.send("GeeksforGeeks");
});
  
app.get('/gfg' , (req , res) => {
    // Creating Full Url.
    var fullLink = req.protocol + "://"
    req.hostname + req.originalUrl;
    res.send(fullLink);
});
  
// Listening App
app.listen(4000 , ()=>{
    console.log("server is running on port 4000");
});


Step 7: Run the server using the following command.

node index.js

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads