Horje
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, GeeksforGeeks!\n');
    });
 
const PORT = 3000;
server.listen(PORT,
    () => {
        console.log(
            `Server running at http://localhost:${PORT}/`
        );
    });

Output:

Hello, GeeksforGeeks!



Reffered: https://www.geeksforgeeks.org


Node.js

Related
How to handle environment variables in Node ? How to handle environment variables in Node ?
What is the purpose of the path module in NodeJS? What is the purpose of the path module in NodeJS?
Explain the concept of middleware in NodeJS Explain the concept of middleware in NodeJS
How to handle streaming data in Node ? How to handle streaming data in Node ?
What is the purpose of the Buffer class in Node ? What is the purpose of the Buffer class in Node ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
10