Skip to main content

Archive

Show more

Node.js HTTP Handling

Node.js HTTP Handling

Node.js provides a built-in HTTP module that allows you to create HTTP servers and handle HTTP requests and responses. With the HTTP module, you can build web servers, API endpoints, and handle various HTTP methods such as GET, POST, PUT, and DELETE.


1. Creating an HTTP Server

You can create an HTTP server using the http.createServer() method. This method takes a callback function that will be invoked whenever a request is received by the server.

Example:

const http = require('http');

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

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

In this example, the server responds with "Hello, World!" to any incoming HTTP request.


2. Handling HTTP Requests

You can handle different types of HTTP requests (e.g., GET, POST, PUT, DELETE) by inspecting the req.method property inside the request handler callback function.

Example:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'GET') {
        // Handle GET request
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('GET request received\n');
    } else if (req.method === 'POST') {
        // Handle POST request
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('POST request received\n');
    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Unsupported HTTP method\n');
    }
});

const PORT = 3000;
server.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});

This example demonstrates how to handle GET and POST requests based on the HTTP method.


3. Conclusion

Node.js HTTP handling allows you to create powerful web servers and handle various HTTP requests and responses. Whether you're building RESTful APIs, serving web pages, or handling AJAX requests, Node.js provides a versatile and efficient platform for handling HTTP communication.

Comments