Skip to content

Commit 96cf0fb

Browse files
committed
buitin middleware
1 parent 3be3bc7 commit 96cf0fb

2 files changed

Lines changed: 45 additions & 0 deletions

File tree

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
const express = require("express");
2+
const app = express();
3+
4+
// Custom middleware: get username header
5+
function usernameMiddleware(req, res, next) {
6+
const username = req.header("X-Username");
7+
req.username = username ? username : null;
8+
next();
9+
}
10+
11+
// Built-in Express middleware to parse JSON
12+
app.post("/", usernameMiddleware, express.json(), (req, res) => {
13+
const username = req.username;
14+
const subjects = req.body;
15+
16+
if (!Array.isArray(subjects)) {
17+
return res.status(400).send("Request body must be a JSON array.");
18+
}
19+
if (!subjects.every(item => typeof item === "string")) {
20+
return res.status(400).send("All array elements must be strings.");
21+
}
22+
23+
const count = subjects.length;
24+
let response = "";
25+
if (username) response += `You are authenticated as ${username}.\n\n`;
26+
else response += "You are not authenticated.\n\n";
27+
28+
if (count === 1) response += `You have requested information about 1 subject: ${subjects[0]}.`;
29+
else if (count > 1) response += `You have requested information about ${count} subjects: ${subjects.join(", ")}.`;
30+
else response += "You have requested information about 0 subjects.";
31+
32+
res.send(response);
33+
});
34+
35+
app.listen(3000, () => {
36+
console.log("✅ Built-in middleware app running on http://localhost:3000");
37+
});
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"name": "builtin_middlewares",
3+
"version": "1.0.0",
4+
"main": "app.js",
5+
"dependencies": {
6+
"express": "^5.1.0"
7+
}
8+
}

0 commit comments

Comments
 (0)