Skip to content

Commit e9f35c7

Browse files
committed
Body middleware
1 parent 7329330 commit e9f35c7

1 file changed

Lines changed: 27 additions & 7 deletions

File tree

middleware-exercises/index.js

Lines changed: 27 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,32 @@ app.use(express.json());
66

77
app.get("/", (req, res) => res.status(200).send("Server is running"));
88

9-
app.post("/", (req, res) => {
10-
req.username = req.headers["x-username"] ?? null;
11-
const message = req.username
12-
? `You are authenticated as ${req.username}`
13-
: "You are not authenticated";
14-
res.status(200).send(message);
15-
});
9+
app.post(
10+
"/",
11+
(req, res, next) => {
12+
req.username = req.headers["x-username"] ?? null;
13+
if (
14+
!Array.isArray(req.body) ||
15+
!req.body.every((item) => typeof item === "string")
16+
) {
17+
return res
18+
.status(400)
19+
.json({ error: "Request body must be a JSON array of strings" });
20+
}
21+
res.locals.body = req.body;
22+
next();
23+
},
24+
(req, res) => {
25+
const auth = req.username
26+
? `You are authenticated as ${req.username}`
27+
: "You are not authenticated";
28+
const data = res.locals.body;
29+
res
30+
.status(200)
31+
.send(
32+
`${auth}\n \nYou have requested information about ${data.length} ${data.length === 1 ? "subject" : "subjects"}: ${data} `,
33+
);
34+
},
35+
);
1636

1737
app.listen(3000, () => console.log("Server is running on port 3000"));

0 commit comments

Comments
 (0)