Page Content

Tutorials

How to handle POST Request in NodeJS?

Understanding POST Requests

Sending information to a server to create or update a resource is the main usage of a POST request, an HTTP method. POST requests transmit information in the request body as opposed to GET requests, which normally retrieve information and may contain information in the URL’s query string. Because the content is not clearly displayed in the URL, POST requests are appropriate for sensitive material and larger data payloads. It is important to handle POST requests carefully when they have a significant impact on the state of an application.

Handling Raw POST Data in Node.js

It is necessary to comprehend streams and event emitters in order to handle incoming POST data in a fundamental Node.js HTTP server. Client data is received as data events in chunks, and the request object itself is a readable stream. In order to handle all of the data, you must gather these pieces in a buffer until the last event, which indicates that all of the data has been received, is released.

Here’s a simplified example of how this works:

const http = require('http'); // Loads the http module 

const PORT = 8080; // Define port number 

const server = http.createServer((request, response) => { // Creates an HTTP server 
  let buffer = ''; // Initialize an empty string to collect data chunks 

  request.on('data', chunk => { // Listen for 'data' events 
    buffer += chunk; // Append each data chunk to the buffer 
  });

  request.on('end', () => { // Listen for the 'end' event when all data is received 
    const responseString = `Received string: ${buffer}`;
    console.log(`Responding with: ${responseString}`); // Log the received data

    response.writeHead(200, { 'Content-Type': 'text/plain' }); // Set HTTP status and content type 
    response.end(responseString); // Send the response back to the client 
  });
});

server.listen(PORT, () => { // Make the server listen on the specified port 
  console.log(`Server listening on http://localhost:${PORT}`); // Log server status 
});

To test this, you could use curl to send a POST request: curl -X POST -d "Here is some data from the form!" http://localhost:8080

Console Output: Server listening on http://localhost:8080 Responding with: Received string: Here is some data from the form!

While this method offers fine-grained control, it can become complicated when dealing with different kinds of form input (such as multipart data for file uploads or URL-encoded data). Web frameworks such as Express.js and specialised middleware are extremely useful in this situation.

Processing Form Data with Express.js and Middleware

Express.js is a simple and adaptable Node.js web application framework that offers a wide range of functionality for creating web applications, such as streamlined request processing and routing. Because Express lets you construct routes using app.get, app.post, app.put, app.delete, and so forth, it makes handling HTTP methods like GET and POST easier.

The body-parser module of middleware is frequently used by Express applications to process form data delivered in POST requests. In the application’s request-response cycle, middleware functions are those that have access to the request object (req), the response object (res), and the subsequent middleware function (next). They have the ability to use next to transfer control to the following function in the chain, execute code, modify the req and res objects, and terminate the response cycle.

Using the req.body attribute, the body-parser middleware parses the incoming request body and makes it available as a JavaScript object.

Depending on the incoming data’s Content-Type, there are several ways to configure the body-parser:

  • bodyParser.json(): This middleware parses incoming requests with JSON payloads using the bodyParser.json() function. For APIs where customers send data in JSON format, it is frequently utilised.
  • bodyParser.urlencoded({ extended: true }): This middleware parses incoming requests (application/x-www-form-urlencoded) with URL-encoded payloads, which is the default content type for data. Arrays and rich objects can be encoded into the URL-encoded format by using the extended: true option.

You can simply access the form fields and their values using req.body in your route handler routines after using the body-parser middleware.

Code Example: Express Server with for Form Data

As an example, let’s look at a common situation where an HTML form sends data to an Express server.

index.html (The HTML Form)

<!DOCTYPE html>
<html>
<head>
    <title>Node.js Form Example</title>
</head>
<body>
    <h1>Submit Your Data</h1>
    <form action="/submit-form" method="POST"> <!-- Form points to /submit-form via POST -->
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="userName" required><br><br>
        
        <label for="email">Email:</label><br>
        <input type="email" id="email" name="userEmail" required><br><br>
        
        <label for="message">Message:</label><br>
        <textarea id="message" name="userMessage" rows="4" cols="50"></textarea><br><br>
        
        <button type="submit">Submit Data</button>
    </form>
</body>
</html>

app.js (The Node.js Express Server)

First, you’ll need to install Express and Body-Parser if you haven’t already: npm install express body-parser --save

const express = require('express'); // Import the express module 
const bodyParser = require('body-parser'); // Import body-parser middleware 
const path = require('path'); // Node.js built-in path module for handling file paths 

const app = express(); // Create an Express application 
const port = 3000; // Define the port for the server to listen on 

// Serve static files (like your index.html) from the current directory 
app.use(express.static(path.join(__dirname))); 

// Use body-parser middleware to parse URL-encoded form data
app.use(bodyParser.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded 

// Optionally, if you also handle JSON submissions:
app.use(bodyParser.json()); // For parsing application/json 

// Define a POST route to handle form submissions
app.post('/submit-form', (req, res) => { // Handles HTTP POST requests to /submit-form 
    console.log('Received form submission:');
    console.log(`Name: ${req.body.userName}`); // Access form field 'userName' via req.body 
    console.log(`Email: ${req.body.userEmail}`); // Access form field 'userEmail'
    console.log(`Message: ${req.body.userMessage}`); // Access form field 'userMessage'

    // Send a response back to the client
    res.send('<h1>Thank you for your submission!</h1><p>Your data has been processed.</p>'); 
});

// Start the server
app.listen(port, () => { // Make the app listen on the defined port 
    console.log(`Server listening on http://localhost:${port}`); // Log server status 
    console.log('Open index.html in your browser to test the form.');
});

To run this example:

  1. Save the HTML code as index.html in a folder.
  2. Save the Node.js code as app.js in the same folder.
  3. Open your terminal or command prompt, navigate to that folder, and run: node app.js
  4. Open your web browser and go to http://localhost:3000/index.html. Fill out the form and submit it.

Expected Console Output (after submitting the form): Server listening on http://localhost:3000 Open index.html in your browser to test the form. Received form submission: Name: John Doe Email: john.doe@example.com Message: This is a test message.

Expected Browser Output (after submitting the form): A page displaying: Thank you for your submission! Your data has been processed.

As you can see, the req.body object cleanly contains the data from the form fields, with keys matching the name attributes of your HTML input elements (e.g., userName, userEmail, userMessage).

Handling File Uploads ()

It’s important to note that the body-parser middleware, while excellent for URL-encoded and JSON data, is not typically used for handling multipart/form-data, which is the encoding type for forms that include file uploads. For such cases, specialized Node.js modules are available, such as multer or formidable. These libraries provide robust solutions for processing file streams and managing the temporary storage of uploaded files.

In Conclusion

Node.js particularly when combined with the Express.js framework and body-parser middleware, offers a straightforward and efficient way to handle incoming POST requests and process data from HTML forms. This abstraction greatly simplifies development compared to handling raw HTTP streams, allowing developers to focus on application logic rather than low-level parsing.

Index