Open In App

Node.js Web Server

Last Updated : 11 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

What is Node.js? 

Node.js is an open-source server environment. Node.js uses JavaScript on the server. The task of a web server is to open a file on the server and return the content to the client.

Node.js has a built-in module called HTTP, which allows Node.js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Example: 

JavaScript




// Import the Node.js http module
const http = require('http');
 
// req is the request object which is
// coming from the client side
// res is the response object which is going
// to client as response from the server
 
// Create a server object
http.createServer(function (req, res) {
 
    // 200 is the status code which means
    // All OK and the second argument is
    // the object of response header.
    res.writeHead(200, { 'Content-Type': 'text/html' });
 
    // Write a response to the client
    res.write('Congrats you have a created a web server');
 
    // End the response
    res.end();
 
}).listen(8081); // Server object listens on port 8081
 
console.log('Node.js web server at port 8081 is running..')


The function passed in the http.createServer() will be executed when the client goes to the url http://localhost:8081

Steps to run the code:

  • Save the above code in a file with a .js extension
  • Open the command prompt and goes to the folder where the file is there using the cd command.
  • Run the command node file_name.js
  • Open the browser and go to the URL http://localhost:8081

 

When http://localhost:8081 is opened in the browser.

  

The http.createServer() method includes a request object that can be used to get information about the current HTTP request e.g. url, request header, and data. 

The following example demonstrates handling HTTP requests and responses in Node.js. 

javascript




// Import Node.js core module i.e http
const http = require('http');
 
// Create web server
const server = http.createServer(function (req, res) {
 
    // Check the URL of the current request
    if (req.url == '/') {
 
        // Set response header
        res.writeHead(200, { 'Content-Type': 'text/html' });
 
        // Set response content   
        res.write(
            `<html><body style="text-align:center;">
            <h1 style="color:green;">GeeksforGeeks Home Page</h1>
            <p>A computer science portal</p>
            </body></html>`);
        res.end();//end the response
 
    }
    else if (req.url == "/webtech") {
 
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`
        <html><body style="text-align:center;">
            <h1 style="color:green;">Welcome to GeeksforGeeks</h1>
            <a href="https://www.geeksforgeeks.org/web-technology/">
            Read Web Technology content
            </a>
        </body></html>`);
        res.end();//end the response
 
    }
    else if (req.url == "/DS") {
 
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`<html><body style="text-align:center;">
        <h1 style="color:green;">GeeksforGeeks</h1>
            Read Data Structures Content
        </a>
        </body></html>`);
        res.end(); //end the response
 
    }
    else if (req.url == "/algo") {
 
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write(`<html><body style="text-align:center;">
        <h1 style="color:green;">GeeksforGeeks</h1>
        Read Algorithm analysis and Design Content
        </a>
    </body></html>`);
        res.end(); //end the response
 
    }
    else
        res.end('Invalid Request!'); //end the response
 
    // Server object listens on port 8081
}).listen(3000, () => console.log('Server running on port 3000'));


In the above example, req.url is used to check the url of the current request, and based on that it sends the response. 

Command to Run code:

node index.js

Output:

  • URL: localhost:3000 

URL: localhost:3000/webtech

 

URL: localhost:3000/DS

 

URL: localhost:3000/algo

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads