Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP).
Nodejs HTTP module used to create an HTTP server, which listen request on specific server port and send response back to the client.
Open the VScode or Visual Studio, and create project in Node.js
npm init
After running the above command, it will ask a couple of questions in the command prompt such as package name, version, entry point, author and more.
npm init package name: (index) version: (1.0.0) description: entry point: (index.js) test command: git repository: keywords: author: license: (ISC)
To prevent asking the above questions, we can use the below command it will create a `package.json` file with the default configuration for us and later we can modify it.
npm init -y
The Anonymous function passed into the `http.createServer()` method, will get executed when someone tries to access the Endpoint of the server on port "8000".
let http = require('http'); // create a server object: http.createServer(function (req, res) { console.log("Server Started"); // write a response to the client res.write('Server Started using HTTP Module!'); res.end(); //end the response }).listen(8000); // the server listens on port 8000
Save the above code in a file named "http-server.js" file.
Nodemon is a tool that restarts automatically Node.js applications when file changes are detected.
To install `nodemon` package in our project. use the below command.
npm install nodemon
Scripts object in `package.json` stores information in `key-value` pairs and helps us to maintain different scripts to run our application in our multiple environments. such as `dev environment`, `prod environment`, `qa environment`, `run test cases locally` and more.
"scripts": { "start": "nodemon http-server.js" },
Run the above code from Command Prompt/Terminal using command: -> "node run start"
Open Browser or Postman, type the endpoint "http://localhost:8000" in the Browser "Search Bar" and press `enter`.
Follow the same steps on your computer to see the same output as mentioned below:
on Console: -> Output: > Server Started on Browser -> Output: "Server Started using HTTP Module!"
If the response from the "HTTP" server is supposed to be sent to the `client/website`, we should include an "HTTP" header with the correct `content type`.
let http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'application/json'}); res.write('Server Started using HTTP Module!'); res.end(); }).listen(8000);
If the response from the `HTTP` server is supposed to be displayed as `HTML`, We should include an "HTTP" header with the correct "content-type".
let http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Server Started using HTTP Module!'); res.end(); }).listen(8000);