|
| 1 | +/* |
| 2 | +Removed custom middleware that manually parsed raw text bodies |
| 3 | +Enabled Express’s built‑in JSON parser |
| 4 | +Updated validation middleware to work with parsed JSON |
| 5 | +Fixed curl command by switching Content-Type |
| 6 | +to application/json (using: curl -X POST http://localhost:3000/subjects |
| 7 | +-H "Content-Type: application/json" |
| 8 | +-H "X-Username: Ahmed" |
| 9 | +--data '["Bees"]') |
| 10 | +*/ |
| 11 | +import express from "express"; |
| 12 | +const app = express(); |
| 13 | +app.use(express.json()); // express builtin JSON parser |
| 14 | + |
| 15 | + |
| 16 | +// Middleware - Extracting username |
| 17 | + |
| 18 | +function usernameMiddleware(req, res, next){ //middleware always has three parameters. req from client, res you send back and a next function that passes controls to next middleware |
| 19 | + const userName = req.header("X-Username"); //getting a custom HTTP Header from the request |
| 20 | + req.userName = userName || null; //if username is not presnet store null |
| 21 | + next(); // this passes control to the next middleware. |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +app.post("/subjects",usernameMiddleware, (req, res) => { |
| 26 | + const userName = req.userName; |
| 27 | + const subjects = req.body; |
| 28 | + const count = subjects.length; |
| 29 | + const authMessage = userName ? `You are authenticated as ${userName}.` : `You are not authenticated.`; |
| 30 | +// Subject message |
| 31 | + let subjectMessage; |
| 32 | + if (count === 0) { |
| 33 | + subjectMessage = "You have requested information about 0 subjects."; |
| 34 | + } else if (count === 1) { |
| 35 | + subjectMessage = `You have requested information about 1 subject: ${subjects[0]}.`; |
| 36 | + } else { |
| 37 | + subjectMessage = `You have requested information about ${count} subjects: ${subjects.join(", ")}.`; |
| 38 | + } |
| 39 | + |
| 40 | + // Send final response |
| 41 | + res.send(`${authMessage}\n\n${subjectMessage}`); |
| 42 | +}); |
| 43 | + |
| 44 | +const PORT = 3000 |
| 45 | +app.listen(PORT, () => { |
| 46 | + console.log(`Server running on http://localhost:${PORT}`) |
| 47 | +}); |
0 commit comments