In Express.js, handling HTTP POST requests is common when dealing with forms and data submissions.
To handle POST requests in Express.js, we need to use the `post()` method to define a route that listens for POST requests. The data sent from the client to server can be accessed from the request body using `req.body`.
const express = require("express"); const app = express();
// Middleware to parse JSON and URL-encoded data app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true, parameterLimit: 50000 })); const PORT = process.env.PORT || 3000;
// Simulating a data store let users = [ { id: 1, name: 'Alice Collin' }, { id: 2, name: 'Edward Collin' }, ]; // Handling a simple GET request at the root URL "/" to fetch all users app.get("/", (req, res) => { console.log("recieve request"); res.send(JSON.stringify(users)); }); // Handling a POST request with form data app.post("/add-user", (req, res) => { const formData = req.body; users.push(formData); res.send(`Form Data Received: ${JSON.stringify(formData)}`); });
// Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
const express = require("express"); const app = express(); // Middleware to parse JSON and URL-encoded data app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true, parameterLimit: 50000 })); const PORT = process.env.PORT || 3000; // Simulating a data store let users = [ { id: 1, name: 'Alice Collin' }, { id: 2, name: 'Edward Collin' }, ]; // Handling a simple GET request at the root URL "/" to fetch all users app.get("/", (req, res) => { console.log("recieve request"); res.send(JSON.stringify(users)); }); // Handling a POST request with form data app.post("/add-user", (req, res) => { const formData = req.body; users.push(formData); res.send(`Form Data Received: ${JSON.stringify(formData)}`); }); // Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.post()" is used to define a route for handling HTTP POST requests.
The "express.json()", "express.urlencoded({extended: true})" middleware is used to parse the request body, making it accessible through "req.body".
The req (request) object provides information about the incoming request, and the res (response) object is used to send a response back to the client.
Handling a get request at the root URL ("/") to fetch all mock users.
Handling a POST request with form data ("/submit"). The express.json(), express.urlencoded({extended: true}) middleware is used to parse the form data from the request body.
// navigate to folder location where server.js exist node server.js