|
| 1 | +import express, { json } from "express"; |
| 2 | + |
| 3 | +const app = express(); |
| 4 | +app.use(express.json()); |
| 5 | +app.use(express.urlencoded({ extended: true })); |
| 6 | + |
| 7 | +function usernameMiddleware(req, res, next) { |
| 8 | + const username = req.get("X-username"); |
| 9 | + req.username = username; |
| 10 | + console.log(username); |
| 11 | + next(); |
| 12 | +} |
| 13 | + |
| 14 | +app.use(usernameMiddleware); |
| 15 | + |
| 16 | +app.post("/", (req, res) => { |
| 17 | + let responseStr = ""; |
| 18 | + if (req.username) { |
| 19 | + responseStr = `You are authenticated as ${req.username}.\n`; |
| 20 | + } else { |
| 21 | + responseStr = `You are not authenticated.\n`; |
| 22 | + } |
| 23 | + |
| 24 | + if (req.body) { |
| 25 | + console.log(req.body); |
| 26 | + responseStr = responseStr.concat( |
| 27 | + `You have requested information about ${req.body.length} subjects: ${req.body.join(", ")}.\n`, |
| 28 | + ); |
| 29 | + } |
| 30 | + res.send(responseStr); |
| 31 | +}); |
| 32 | + |
| 33 | +/* |
| 34 | +previous CURL does not work because curl --data sends 'content-type: application/x-www-form-urlencoded', is not parsed by expres.json() |
| 35 | +but by urlencoded(), which tries to create a key:value pair set rather than an array. |
| 36 | +
|
| 37 | +By setting the content type explicitly, this can force the app to use the desired middleware: |
| 38 | +
|
| 39 | +curl -X POST http://localhost:3000/ \ |
| 40 | + -H "Content-Type: application/json" \ |
| 41 | + -H "X-Username: Ahmed" \ |
| 42 | + --data '["Bees", "birds", "lizards"]' |
| 43 | +*/ |
| 44 | + |
| 45 | +app.listen(3000, () => { |
| 46 | + console.log(`Listening on port: 3000`); |
| 47 | +}); |
0 commit comments