Skip to content

Commit bd66013

Browse files
committed
Implement express built in JSON middle and fix the request with curl.
1 parent 755341e commit bd66013

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

midlleware-Ex2/server.js

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
const express = require("express");
2+
3+
const app = express();
4+
app.use(express.json()); //built in JSON parser
5+
const PORT = 3000;
6+
7+
function usernameMiddleware(req, res, next) {
8+
const headerValue = req.header("X-Username"); // Express helper for headers
9+
req.username = headerValue ? headerValue : null;
10+
next();
11+
}
12+
13+
app.post("/", usernameMiddleware, (req, res) => {
14+
// Validate: must be array of strings
15+
if (
16+
!Array.isArray(req.body) ||
17+
!req.body.every((x) => typeof x === "string")
18+
) {
19+
return res
20+
.status(400)
21+
.type("text")
22+
.send("Invalid body. Expected a JSON array of strings.");
23+
}
24+
25+
const username = req.username;
26+
const authLine = username
27+
? `You are authenticated as ${username}.`
28+
: `You are not authenticated.`;
29+
30+
const subjects = req.body; // should be an array of strings
31+
const count = subjects.length;
32+
33+
let subjectsLine = `You have requested information about ${count} subject${count === 1 ? "" : "s"}`;
34+
subjectsLine += count > 0 ? `: ${subjects.join(", ")}.` : `.`;
35+
36+
res.type("text").send(`${authLine}\n\n${subjectsLine}`);
37+
});
38+
39+
app.listen(PORT, () => {
40+
console.log(`Listening on http://localhost:${PORT}`);
41+
});

0 commit comments

Comments
 (0)