0
0
ExpressDebug / FixBeginner · 4 min read

How to Handle PUT Request in Express API: Fix and Best Practices

To handle a 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.

javascript
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);
Output
req.body is undefined, so updatedItem is undefined and update data is missing.
🔧

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.

javascript
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');
});
Output
Updated item with id 123 and data: {"name":"New Name","price":100}
🛡️

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.

Key Takeaways

Use app.put() to handle PUT requests in Express.
Include express.json() middleware to parse JSON request bodies.
Always test your API endpoints with real PUT requests.
Use correct HTTP methods matching your API design.
Check for JSON syntax errors in client requests.