How to Handle PUT Request in Express API: Fix and Best Practices
PUT request in an Express API, use app.put(path, handler) where handler processes the request and sends a response. Make sure to use middleware like express.json() to parse JSON request bodies before accessing req.body.Why This Happens
Developers often forget to use the express.json() middleware, so req.body is undefined when handling PUT requests. Also, using app.get() or app.post() instead of app.put() for a PUT request causes the handler not to run.
import express from 'express'; const app = express(); app.put('/item/:id', (req, res) => { // Trying to access req.body without parsing middleware const updatedItem = req.body; res.send(`Updated item with id ${req.params.id}`); }); app.listen(3000);
The Fix
Add express.json() middleware to parse JSON bodies before your routes. Use app.put() to handle PUT requests properly. This allows you to access req.body and update resources as expected.
import express from 'express'; const app = express(); // Middleware to parse JSON request bodies app.use(express.json()); app.put('/item/:id', (req, res) => { const updatedItem = req.body; res.send(`Updated item with id ${req.params.id} and data: ${JSON.stringify(updatedItem)}`); }); app.listen(3000, () => { console.log('Server running on port 3000'); });
Prevention
Always include express.json() middleware early in your Express app to parse JSON bodies. Use the correct HTTP method handlers like app.put() for PUT requests. Test your API endpoints with tools like Postman or curl to verify request handling.
Use linting tools and follow Express best practices to avoid missing middleware or wrong method handlers.
Related Errors
1. req.body is undefined: Happens when body parsing middleware is missing.
2. 404 Not Found on PUT request: Using app.post() or app.get() instead of app.put() for the route.
3. Syntax errors in JSON body: Client sends invalid JSON causing parsing errors.