How to Use app.put in Express for HTTP PUT Requests
Use
app.put(path, callback) in Express to handle HTTP PUT requests at a specific path. The callback function receives the request and response objects to update data and send a response.Syntax
The app.put() method defines a route handler for HTTP PUT requests. It takes two main parts:
- path: The URL path where the PUT request is handled.
- callback: A function with
reqandresparameters to process the request and send a response.
javascript
app.put(path, (req, res) => {
// handle update logic here
res.send('Resource updated');
});Example
This example shows a simple Express server that updates a user's name using app.put. It reads the new name from the request body and sends a confirmation response.
javascript
import express from 'express'; const app = express(); app.use(express.json()); let user = { id: 1, name: 'Alice' }; app.put('/user/:id', (req, res) => { const userId = Number(req.params.id); if (userId === user.id) { user.name = req.body.name || user.name; res.json({ message: 'User updated', user }); } else { res.status(404).json({ message: 'User not found' }); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
Common Pitfalls
Common mistakes when using app.put include:
- Not parsing JSON body with
express.json(), soreq.bodyis undefined. - Using
app.postorapp.getinstead ofapp.putfor update operations. - Not handling the case when the resource to update does not exist.
javascript
/* Wrong: Missing express.json middleware */ app.put('/item/:id', (req, res) => { // req.body will be undefined res.send('Update attempted'); }); /* Right: Include express.json to parse JSON body */ app.use(express.json()); app.put('/item/:id', (req, res) => { // req.body is available here res.send('Update successful'); });
Quick Reference
Tips for using app.put effectively:
- Use
app.putfor full updates of a resource. - Always parse JSON body with
express.json()middleware. - Validate input data before updating.
- Send appropriate HTTP status codes (e.g., 200 for success, 404 if resource not found).
Key Takeaways
Use app.put(path, callback) to handle HTTP PUT requests for updating resources.
Always include express.json() middleware to parse JSON request bodies.
Validate resource existence and input data before updating.
Send clear responses with proper HTTP status codes.
app.put is for full updates; use app.patch for partial updates.