Open In App

How to Build a Simple Web Server with Node.js ?

Last Updated : 25 Jun, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction: Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework, and it’s not a programming language. Node.js is mostly used in server-side programming. In this article, we will discuss how to make a web server using node.js.

Creating Web Servers Using NodeJS: There are mainly two ways as follows.

  1. Using http inbuilt module
  2. Using express third party module

Using http module: HTTP and HTTPS, these two inbuilt modules are used to create a simple server. The HTTPS module provides the feature of the encryption of communication with the help of the secure layer feature of this module. Whereas the HTTP module doesn’t provide the encryption of the data.

Project structure: It will look like this.

index.js




// Importing the http module
const http = require("http")
  
// Creating server 
const server = http.createServer((req, res) => {
    // Sending the response
    res.write("This is the response from the server")
    res.end();
})
  
// Server listening to port 3000
server.listen((3000), () => {
    console.log("Server is Running");
})


Run index.js file using below command:

node index.js

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

Using express module: The express.js is one of the most powerful frameworks of the node.js that works on the upper layer of the http module. The main advantage of using express.js server is filtering the incoming requests by clients.

Installing module: Install the required module using the following command.

npm install express

Project structure: It will look like this.

index.js




// Importing express module
const express = require("express")
const app = express()
  
// Handling GET / request
app.use("/", (req, res, next) => {
    res.send("This is the express server")
})
  
// Handling GET /hello request
app.get("/hello", (req, res, next) => {
    res.send("This is the hello response");
})
  
// Server setup
app.listen(3000, () => {
    console.log("Server is Running")
})


Run the index.js file using the below command:

node index.js

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:



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

Similar Reads