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

KISHAN RAMLAKHAN NISHAD - Nov 2 - - Dev Community

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.

Table of Content

Using Built-in HTTP module
Using Express Module

Using Built-in 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.

`// Filename - 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");
})

`

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.

// Filename - 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")
})

.
Terabox Video Player