Our current project should already have the database connection from Lesson 2. Now we need to add the JSON parsing middleware that we covered in Module 1.
Add the express.json() middleware before your routes:
// imports and other code
// Add JSON parsing middleware (from Module 1)
app.use(express.json());
// Your existing GET routes from Lesson 2
app.get("/users", async (req, res) => {
// ... existing code
});
Why we need express.json()
- In Module 1 we learned this middleware parses JSON from request bodies.
- POST, PUT, and PATCH requests send data in req.body.
- Without this middleware, req.body would be undefined.