In Express.js, handling HTTP PUT requests is common for updating existing resources.
To handle `PUT` requests in Express.js, we can use the `put()` method to define a route that listens for PUT requests. Like POST requests, the data sent from the client to the 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 PUT request to update user data by ID app.put('/user/:id', (req, res) => { const userId = parseInt(req.params.id); const updatedUserData = req.body; // Finding the user by ID const userToUpdate = users.find(user => user.id === userId); // Updating the user data if found if (userToUpdate) { userToUpdate.name = updatedUserData.name; res.send(`User with ID ${userId} updated successfully.`); } else { res.status(404).send(`User with ID ${userId} not found.`); } });
// 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 PUT request to update user data by ID app.put('/user/:id', (req, res) => { const userId = parseInt(req.params.id); const updatedUserData = req.body; // Finding the user by ID const userToUpdate = users.find(user => user.id === userId); // Updating the user data if found if (userToUpdate) { userToUpdate.name = updatedUserData.name; res.send(`User with ID ${userId} updated successfully.`); } else { res.status(404).send(`User with ID ${userId} not found.`); } }); // Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
"app.put()" is used to define a route for handling HTTP PUT requests.
The "express.json()" and "express.urlencoded({ extended: true })" middleware is used to parse the request body, making it accessible through "req.body".
The route "/user/:id" expects a parameter id in the URL, representing the user's ID that needs to be updated.
The server simulates a data store (in-memory array users), and the PUT request updates the user's data based on the provided ID.
// navigate to folder location where server.js exist node server.js