NodeJS - Quick Start- Web development
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.