Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Node.js HTTP Request Handling

Tech 1

To handle HTTP requests in Node.js, we utilize the built-in http module. This guide walks you through creating a server, handling GET requests with query parameters, processing POST requests, and a combined example.

1. Creating an HTTP Server

The http module in Node.js enables us to set up an HTTP server. Here's a basic example (save as server.js):

const http = require('http');

// Create a server instance. The callback takes (request, response) as parameters
const httpServer = http.createServer((req, res) => {
  // Send a response to the client
  res.end('Hello from Node.js Server!');
});

// Listen on port 8000. The callback logs the server address
httpServer.listen(8000, () => {
  console.log('Server running at http://localhost:8000');
});

Explanation:

  • We import the http module using CommonJS require.
  • createServer accepts a callback with request (incoming client request) and response (server’s response to the client) objects.
  • res.end() sends a response to the client.
  • listen(8000,...) starts the server on port 8000.

To run:

node server.js

Access http://localhost:8000 in your browser to see "Hello from Node.js Server!".

2. Handling GET Requests with Query Parameters

GET requests often include parameters in the URL (e.g., ?key=value). To parse these, use the node:querystring module.

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

const httpServer = http.createServer((req, res) => {
  const httpMethod = req.method;
  console.log('Request method:', httpMethod);

  const requestUrl = req.url;
  console.log('Request URL:', requestUrl);

  // Split the URL to get query parameters
  const queryPart = requestUrl.split('?')[1];
  const parsedQuery = querystring.parse(queryPart);
  console.log('Parsed query:', parsedQuery);

  // Send the parsed query as JSON response
  res.end(JSON.stringify(parsedQuery));
});

httpServer.listen(8000, () => {
  console.log('Server ready at http://localhost:8000');
});

Test it by visiting http://localhost:8000?name=Alice&age=30 in your browser. The server parses the name and age parameters and returns them as JSON.

3. Handling POST Requests

POST requests send data in the request body (not in the URL). Use req.on('data') to read the body and req.on('end') when data transmission finishes.

const http = require('http');

const httpServer = http.createServer((req, res) => {
  if (req.method === 'POST') {
    console.log('Content-Type:', req.headers['content-type']);

    let requestBody = '';
    req.on('data', (chunk) => {
      requestBody += chunk.toString();
    });

    req.on('end', () => {
      console.log('Received POST data:', requestBody);
      res.end('POST request processed successfully!');
    });
  } else {
    res.end('Only POST requests are supported here.');
  }
});

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

Use Postman to send a POST request to http://localhost:8000 with a JSON body (e.g., {"message": "Hello POST"}). The server logs the received data.

4. Combined Example (Handle GET and POST)

This example handles both GET (with queries) and POST (with body data):

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

const httpServer = http.createServer((req, res) => {
  const httpMethod = req.method;
  const requestUrl = req.url;
  const [path, queryStr] = requestUrl.split('?');
  const parsedQuery = querystring.parse(queryStr);

  // Set response format to JSON
  res.setHeader('Content-Type', 'application/json');

  const responseData = {
    method: httpMethod,
    url: requestUrl,
    path: path,
    query: parsedQuery,
  };

  if (httpMethod === 'GET') {
    res.end(JSON.stringify(responseData));
  } else if (httpMethod === 'POST') {
    let requestBody = '';
    req.on('data', (chunk) => {
      requestBody += chunk.toString();
    });

    req.on('end', () => {
      responseData.body = JSON.parse(requestBody);
      res.end(JSON.stringify(responseData));
    });
  }
});

httpServer.listen(8000, () => {
  console.log('Combined server running at http://localhost:8000');
});
  • For GET: Visit http://localhost:8000/profile?username=Bob&role=admin to see parsed query data.
  • For POST: Use Postman to send a JSON body (e.g., {"task": "Learn Node.js"}). The server returns combnied data (method, URL, query, and body).
Tags: Node.jshttp

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.