Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
66 changes: 66 additions & 0 deletions middleware-exercises/Custom-Middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
const express = require("express");

const app = express();
const PORT = 3000;

// Middleware 1:check X-Username header
function usernameMiddleware(req, res, next) {
const username = req.get("X-Username");

if (username) {
req.username = username;
} else {
req.username = null;
}

next();
}

// Middleware 2: parse and validate JSON array
function bodyMiddleware(req, res, next) {
let body = "";

req.on("data", (chunk) => {
body += chunk;
});

req.on("end", () => {
try {
const parsedBody = JSON.parse(body);

if (!Array.isArray(parsedBody)) {
return res.status(400).send("Request body must be a JSON array.");
}

if (!parsedBody.every((item) => typeof item === "string")) {
return res.status(400).send("Array must contain only strings.");
}

req.body = parsedBody;
next();
} catch (error) {
res.status(400).send("Request body must be valid JSON.");
}
});
}

app.use(usernameMiddleware);
app.use(bodyMiddleware);

app.post("/", (req, res) => {
const subjects = req.body;
const authenticationMessage = req.username
? `You are authenticated as ${req.username}.`
: "You are not authenticated.";

res.send(
`${authenticationMessage}\n\n` +
`You have requested information about ${subjects.length} ` +
`${subjects.length === 1 ? "subject" : "subjects"}` +
`${subjects.length > 0 ? ": " + subjects.join(", ") : ""}.`,
);
});

app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
56 changes: 56 additions & 0 deletions middleware-exercises/Off-shell-middlewares.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import express from "express";

const app = express();

function usernameMiddleware(req, res, next) {
const username = req.get("X-Username");

if (username) {
req.username = username;
} else {
req.username = null;
}

next();
}

app.use(express.json());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does express.json() do all of the checks you did in your original code?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

express.json() handles parsing and malformed JSON, but it doesn’t validate the expected structure. I’ve added a middleware after it that checks the body is an array of strings and returns 400 if it isn’t.Thanks @LonMcGregor


function bodyValidationMiddleware(req, res, next) {
if (!Array.isArray(req.body)) {
return res.status(400).send("Request body must be a JSON array.");
}

if (!req.body.every((item) => typeof item === "string")) {
return res.status(400).send("Array must contain only strings.");
}

next();
}

app.use(bodyValidationMiddleware);
app.use(usernameMiddleware);

app.post("/", (req, res) => {
const subjects = req.body;

if (req.username) {
res.send(
`You are authenticated as ${req.username}.\n\n` +
`You have requested information about ${subjects.length} ` +
`${subjects.length === 1 ? "subject" : "subjects"}` +
`${subjects.length > 0 ? `: ${subjects.join(", ")}` : ""}.`,
);
} else {
res.send(
`You are not authenticated.\n\n` +
`You have requested information about ${subjects.length} ` +
`${subjects.length === 1 ? "subject" : "subjects"}` +
`${subjects.length > 0 ? `: ${subjects.join(", ")}` : ""}.`,
);
}
});

app.listen(3000, () => {
console.log("Server running on http://localhost:3000");
});
Loading
Loading