NodeJS HTTP Module


What is the HTTP module in Node.js?

The HTTP module in Node.js provides the functionality to create HTTP servers and handle HTTP requests and responses. It is part of Node.js's core modules, meaning you don’t need to install it separately. The module allows developers to build web servers that can handle requests, such as GET, POST, and other HTTP methods.


How do you create a simple HTTP server in Node.js?

To create a basic HTTP server in Node.js, you use the http.createServer() method from the HTTP module. This method creates a server that listens for HTTP requests and sends responses.

Here is an example of creating a simple server:

const http = require('http');

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

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

This server listens on port 3000 and responds with 'Hello, World!' for every request.


How do you handle different HTTP methods (GET, POST) in Node.js?

To handle different HTTP methods, you can inspect the req.method property in the request object. Based on the method (e.g., GET, POST), you can define different logic for handling the request.

Example of handling GET and POST requests:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Handling GET request');
    } else if (req.method === 'POST') {
        let body = '';
        req.on('data', (chunk) => {
            body += chunk.toString();
        });
        req.on('end', () => {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/plain');
            res.end('Handling POST request with data: ' + body);
        });
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

How do you send JSON data in an HTTP response?

To send JSON data in an HTTP response, set the content type header to application/json and use JSON.stringify() to convert a JavaScript object into a JSON string.

Example of sending a JSON response:

const http = require('http');

const server = http.createServer((req, res) => {
    const data = {
        message: 'Hello, World!',
        status: 200
    };
    
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(data));
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

This will send a JSON response that looks like:


{
    "message": "Hello, World!",
    "status": 200
}

How do you handle URL routing in Node.js with the HTTP module?

To handle different routes in Node.js, you can inspect the req.url property and define specific logic for each route. By checking the URL, you can create different responses for different paths.

Example of basic routing:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Welcome to the homepage!');
    } else if (req.url === '/about') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Welcome to the about page!');
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

How do you handle query parameters in a URL with Node.js?

Query parameters in a URL can be parsed using the url module in Node.js. You can use url.parse() to extract the query string and querystring.parse() to turn the query string into an object.

Example of handling query parameters:

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

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url);
    const queryParams = querystring.parse(parsedUrl.query);
    
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(queryParams));
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

If the URL is http://localhost:3000/?name=John&age=30, the server will respond with:


{
    "name": "John",
    "age": "30"
}

How do you handle form data in Node.js with the HTTP module?

To handle form data sent in an HTTP POST request, you need to listen for the 'data' and 'end' events on the req object. You can use the querystring module to parse URL-encoded form data.

Example of handling form data:

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

const server = http.createServer((req, res) => {
    if (req.method === 'POST') {
        let body = '';
        
        req.on('data', (chunk) => {
            body += chunk.toString();
        });
        
        req.on('end', () => {
            const parsedData = querystring.parse(body);
            res.statusCode = 200;
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(parsedData));
        });
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

If a form submits data like name=John&age=30, the server will respond with:


{
    "name": "John",
    "age": "30"
}

How do you handle file uploads in Node.js using the HTTP module?

The HTTP module in Node.js does not natively support file uploads. To handle file uploads, you typically use third-party libraries like formidable or multer. These libraries parse incoming file data and provide a simple API to handle file uploads efficiently.

Example using formidable:

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

const server = http.createServer((req, res) => {
    if (req.method === 'POST') {
        const form = new formidable.IncomingForm();
        
        form.parse(req, (err, fields, files) => {
            if (err) {
                res.statusCode = 500;
                res.end('Error parsing file');
            } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify({ fields, files }));
            }
        });
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

This example uses the formidable library to handle file uploads in Node.js.

Ads