NodeJS HTTP server

Node.js includes a built-in module named http for constructing a NodeJS HTTP server. This module makes it simple for developers to design servers that can handle HTTP requests and answers. In this post, we’ll go through how to create an HTTP server in Node.js, give some examples of how to utilize it, and look at some typical use cases.

Creating an HTTP Server

It is simple to set up an HTTP server with Node.js. The first step is to include the http module in your code. Then, to build a new server, use the http.createServer() function. The method only accepts one argument, a callback function that is called for each incoming request. A request object and a response object are sent to the callback function.

Here’s an example of a simple HTTP server that listens on port 3000 and answers to every incoming request with “Hello World!” :

const http = require('http');

const server = http.createServer((req, res) => {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World!');
});

server.listen(3000, () => {
    console.log('Server listening on port 3000');
});

Handling Requests

After you’ve constructed an HTTP server, you may handle incoming requests by listening for request object events. For example, you can use the req.url property to determine the requested URL and respond with different content based on the URL.

Here’s an example of an HTTP server that supports various routes and responds appropriately:

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
    const pathname = url.parse(req.url).pathname;

    if(pathname === '/') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('Welcome to the home page!');
    } else if(pathname === '/about') {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('This is the about page.');
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('404 - Page Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server listening on port 3000');
});

Parsing Request Data

You may need to parse the data supplied in the request body in some circumstances. Node.js has a querystring module that may be used to parse data given in the request body. An HTTP server that parses data supplied in a POST request is shown below:

const http = require('http');
const querystring = require('querystring');

const server = http.createServer((req, res) => {
    if(req.method === 'POST') {
        let body = '';
        req.on('data', (data) => {
            body += data;
        });
        req.on('end', () => {
            const postData = querystring.parse(body);
            console.log(postData);
            res.end('Data received');
        });
   } else {
      res.writeHead(404, {'Content-Type': 'text/plain'});
      res.end('404 - Page Not Found');
    }
});

server.listen(3000, () => {
console.log('Server listening on port 3000');
});

In this example, the server waits for a ‘data’ event on the request object and appends the data to a variable called ‘body’. When the request is complete, the server parses the data with the ‘querystring.parse()’ function and reports the results to the console.

Q&A

Q: How do I create an HTTP server in Node.js?
A: To create an HTTP server in Node.js, you can use the http.createServer() method and pass in a callback function that takes in a request and response object as arguments. You can then handle incoming requests by listening for events on the request object.

Q: How can I parse data sent in a request body?
A: Node.js provides a built-in module called querystring that can be used to parse data sent in a request body. You can use the querystring.parse() method to parse the data.

Exercises

  1. Create an HTTP server that provides a JSON object containing user information when the route ‘/user’ is accessed.
  2. Build an HTTP server that reads a file from the file system and returns it as a response when the ‘/file’ route is accessed.
  3. Build an HTTP server that receives a POST request containing a JSON object and returns the JSON object in a stringified manner.

1.

javascript const http = require('http'); 
const server = http.createServer((req, res) => { 
  if(req.url === '/user' && req.method === 'GET') { 
    res.writeHead(200, {'Content-Type': 'application/json'}); 
    const user = { name: 'John Doe', age: 30, occupation: 'Developer' } 
    res.end(JSON.stringify(user)); } else { res.writeHead(404, {'Content-Type': 'text/plain'}); 
    res.end('404 - Page Not Found'); } 
  }); 
    server.listen(3000, () => { console.log('Server listening on port 3000'); }
);

2.

const http = require('http');
const fs = require('fs');
const server = http.createServer((req, res) => {
    if(req.url === '/file' && req.method === 'GET') {
        fs.readFile('./file.txt', (err, data) => {
            if(err) {
                res.writeHead(500, {'Content-Type': 'text/plain'});
                res.end('Error reading file');
            } else {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end(data);
            }
        });
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('404 - Page Not Found');
    }
});
server.listen(3000, () => {
    console.console.log('Server listening on port 3000');
});

3.

3.
```javascript
const http = require('http');
const server = http.createServer((req, res) => {
    if(req.url === '/' && req.method === 'POST') {
        let body = '';
        req.on('data', (data) => {
            body += data;
        });
        req.on('end', () => {
            const postData = JSON.parse(body);
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(JSON.stringify(postData));
        });
    } else {
        res.writeHead(404, {'Content-Type': 'text/plain'});
        res.end('404 - Page Not Found');
    }
});
server.listen(3000, () => {
    console.log('Server listening on port 3000');
});

The server listens for a GET request on the path ‘/user’ in the first exercise and responds with a JSON object containing user information. In the second example, the server listens for a GET request on the URL ‘/file’ and uses the fs module to read a file from the file system. It then answers with the file’s content. The server listens for a POST request on the root route ‘/’ in the third exercise, reads the incoming data, parses it as a JSON object, and returns with the same JSON object in a stringified manner.

Youtube
Scroll to Top