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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
package-lock.json
47 changes: 47 additions & 0 deletions builtinmiddleware/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
Removed custom middleware that manually parsed raw text bodies
Enabled Express’s built‑in JSON parser
Updated validation middleware to work with parsed JSON
Fixed curl command by switching Content-Type
to application/json (using: curl -X POST http://localhost:3000/subjects
-H "Content-Type: application/json"
-H "X-Username: Ahmed"
--data '["Bees"]')
*/
import express from "express";
const app = express();
app.use(express.json()); // express builtin JSON parser


// Middleware - Extracting username

function usernameMiddleware(req, res, next){ //middleware always has three parameters. req from client, res you send back and a next function that passes controls to next middleware
const userName = req.header("X-Username"); //getting a custom HTTP Header from the request
req.userName = userName || null; //if username is not presnet store null
next(); // this passes control to the next middleware.
}


app.post("/subjects",usernameMiddleware, (req, res) => {
const userName = req.userName;
const subjects = req.body;
const count = subjects.length;
const authMessage = userName ? `You are authenticated as ${userName}.` : `You are not authenticated.`;
// Subject message
let subjectMessage;
if (count === 0) {
subjectMessage = "You have requested information about 0 subjects.";
} else if (count === 1) {
subjectMessage = `You have requested information about 1 subject: ${subjects[0]}.`;
} else {
subjectMessage = `You have requested information about ${count} subjects: ${subjects.join(", ")}.`;
}

// Send final response
res.send(`${authMessage}\n\n${subjectMessage}`);
});

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

//1st Middleware - Extracting username

function usernameMiddleware(req, res, next){ //middleware always has three parameters. req from client, res you send back and a next function that passes controls to next middleware
const userName = req.header("X-Username"); //getting a custom HTTP Header from the request
req.userName = userName || null; //if username is not presnet store null
next(); // this passes control to the next middleware.
}

//2nd Middleware - Validating JSON array body
function jsonArrayMiddleware(req, res, next){
let data;
try {
data = JSON.parse(req.body);
}
catch(err){
return res.status(400).send("Body must be valid JSON");
}
if(!Array.isArray(data)){
return res.status(400).send("Body must be JSON array");

}
if (!data.every(item => typeof item === "string")) { //every item in the array is a string = NOT TRUE
return res.status(400).send("Array must contain only strings");
}
req.body = data; //store validated array
next() //allows req to continue to next middleware
}

// POST route using both middlewares
app.post("/subjects",usernameMiddleware, jsonArrayMiddleware, (req, res) => {
const userName = req.userName;
const subjects = req.body;
const count = subjects.length;
const authMessage = userName ? `You are authenticated as ${userName}.` : `You are not authenticated.`;
// Subject message
let subjectMessage;
if (count === 0) {
subjectMessage = "You have requested information about 0 subjects.";
} else if (count === 1) {
subjectMessage = `You have requested information about 1 subject: ${subjects[0]}.`;
} else {
subjectMessage = `You have requested information about ${count} subjects: ${subjects.join(", ")}.`;
}

// Send final response
res.send(`${authMessage}\n\n${subjectMessage}`);
});

const PORT = 3000
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`)
});
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"dependencies": {
"express": "^5.2.1"
}
}