NodeJS - Quick Start- Web development


A node.js web application contains the following three components:

Import required modules: The "require" directive is utilized to load a Node.js module.

Engender server: You have to establish a server that will listen to the client's request akin to Apache HTTP Server.

Read request and return replication: The server engendered in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the replication.

Example 1:

index.js

var http = require("http");

http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: application/json
response.writeHead(200, { "Content-Type": "application/json" });
var otherArray = ["Java", "Kotlin"];
var otherObject = { item1: "Angular", item2: "React Native" };
var json = JSON.stringify({
anObject: otherObject,
anArray: otherArray,
another: "Javascript"
});
// Send the response
response.end(json);

}).listen(8083);

// Console will print the message
console.log('Server running at http://127.0.0.1:8083/');

Now execute the index.js to start the server as follows −
$ node index.js

Verify the Output. The server has started.
Server running at http://127.0.0.1:8083/

Make a Request to the Node.js Server using Postman


Example 2:

index.js

var http = require("http");

http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, { 'Content-Type': 'text/plain' });

// Send the response body as "Greetings from knowledgefactory"
response.end('Greetings from knowledgefactory');
}).listen(8084);

// Console will print the message
console.log('Server running at http://127.0.0.1:8084/');

Now execute the index.js to start the server as follows −
$ node index.js

Verify the Output. The server has started.
Server running at http://127.0.0.1:8084/

Open http://127.0.0.1:8084/ in any browser and observe the following result.


More...

NodeJS - Angular - VueJS - ReactJS

Python - Flask  - Angular - VueJS - ReactJS

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete