|
| 1 | +const express = require("express"); |
| 2 | +const app = express(); |
| 3 | + |
| 4 | +// Use built-in JSON middleware |
| 5 | +app.use(express.json()); // Read the request body, parses it as JSON, automatically sets req.body, rejects invalid JSON with 400 |
| 6 | + |
| 7 | +/** |
| 8 | + * Middleware 1: |
| 9 | + * Read X-Username header and attach it to req.username |
| 10 | + */ |
| 11 | +const usernameMiddleware = (req, res, next) => { |
| 12 | + const username = req.header("X-Username"); |
| 13 | + req.username = username ? username : null; |
| 14 | + next(); |
| 15 | +}; |
| 16 | + |
| 17 | +/** |
| 18 | + * Middleware 2 (validation only): |
| 19 | + * Ensure body is an array of strings |
| 20 | + */ |
| 21 | + |
| 22 | +// We still need to validate the shape of the data |
| 23 | +const validateStringArrayBody = (req, res, next) => { |
| 24 | + if (!Array.isArray(req.body)) { |
| 25 | + return res.status(400).send("Request body must be a JSON array"); |
| 26 | + } |
| 27 | + |
| 28 | + if (!req.body.every(item => typeof item === "string")) { |
| 29 | + return res.status(400).send("Array must contain only strings"); |
| 30 | + } |
| 31 | + |
| 32 | + next(); |
| 33 | + |
| 34 | +}; |
| 35 | + |
| 36 | +/** |
| 37 | + * POST endpoint |
| 38 | + */ |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | +app.post( |
| 43 | + "/", |
| 44 | + usernameMiddleware, |
| 45 | + validateStringArrayBody, |
| 46 | + (req, res) => { |
| 47 | + const username = req.username ?? "Anonymous"; |
| 48 | + const subjects = req.body; |
| 49 | + |
| 50 | + res.send( |
| 51 | +`You are authenticated as ${username}. |
| 52 | +
|
| 53 | +You have requested information about ${subjects.length} subjects: ${subjects.join(", ")}.` |
| 54 | + ); |
| 55 | + } |
| 56 | +); |
| 57 | + |
| 58 | +app.listen(3000, () => { |
| 59 | + console.log("Server running on port 3000"); |
| 60 | +}); |
0 commit comments