How to create a simple HTTP server in Node ?
NodeJS provides a straightforward way to create HTTP servers, allowing developers to build web applications and APIs without relying on external web servers like Apache or Nginx. Let’s explore how to create a simple HTTP server in NodeJS.
Steps to Create a NodeJS Server:
Step 1: Initialize the NPM using the below command. Using this the package.json file will be created.
npm init -y
Step 2: Import the HTTP Module:
const http = require('http');
Step 3: Create a Server using the http.createServer()
method to create an HTTP server. This method takes a callback function as an argument, which will be invoked for each incoming HTTP request.
const server = http.createServer((request, response) => {
// Request handling logic
});
Step 4: Handle Requests:
const server = http.createServer((request, response) => {
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end('Hello, World!\n');
});
Example: After implementing the above steps, we will effectively establish the NodeJS server:
Javascript
const http = require( 'http' ); const server = http.createServer( (request, response) => { response.writeHead( 200, { 'Content-Type' : 'text/plain' } ); response.end( 'Hello, w3wiki!\n' ); }); const PORT = 3000; server.listen(PORT, () => { console.log( `Server running at http: //localhost:${PORT}/` ); }); |
Output:
Hello, w3wiki!