Node.js | Web Server

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Import the Node.js http module
var 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..')

chevron_right


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 .js extension
  • Open the command prompt and goes to the folder where the file is there using cd command.
  • Run the command node file_name.js
  • Open the browser and go the url http://localhost:8081

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

The http.createServer() method includes 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 request and response in Node.js.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Import Node.js core module i.e http
var http = require('http');
   
// Create web server
var 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>
          <a href="https://www.geeksforgeeks.org/data-structures/">
            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'));

chevron_right


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



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.