Skip to content

Commit 4579661

Browse files
Added two new directories:
1. Middleware-custom: Express app with two custom-written middlewares (username and JSON array parser) 2. Middleware-offTheShelf: Express app replacing JSON parser with Express's built-in middleware - Both apps handle POST requests and return authentication and subject info messages
1 parent 16ace89 commit 4579661

File tree

7 files changed

+1624
-0
lines changed

7 files changed

+1624
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
node_modules/

Middleware-custom/app.js

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const express = require('express');
2+
const app = express();
3+
const PORT = 3000;
4+
5+
// Middleware 1: Check username header
6+
app.use((req, res, next) => {
7+
req.username = req.headers['x-username'] || null;
8+
next();
9+
});
10+
11+
// Middleware 2: Parse JSON and check if body is string array
12+
app.use((req, res, next) => {
13+
if (req.method !== 'POST') return next();
14+
15+
let body = '';
16+
req.on('data', chunk => {
17+
body += chunk.toString();
18+
});
19+
20+
req.on('end', () => {
21+
try {
22+
req.body = JSON.parse(body);
23+
} catch (error) {
24+
return res.status(400).send('Error: Invalid JSON');
25+
}
26+
27+
// Simple array check
28+
if (!Array.isArray(req.body)) {
29+
return res.status(400).send('Error: Send a JSON array');
30+
}
31+
32+
// Simple string check
33+
for (let item of req.body) {
34+
if (typeof item !== 'string') {
35+
return res.status(400).send('Error: All items must be strings');
36+
}
37+
}
38+
39+
req.subjects = req.body;
40+
next();
41+
});
42+
});
43+
44+
// POST endpoint
45+
app.post('/', (req, res) => {
46+
const name = req.username ? `authenticated as ${req.username}` : 'not authenticated';
47+
const count = req.subjects.length;
48+
const word = count === 1 ? 'subject' : 'subjects';
49+
const list = req.subjects.join(', ');
50+
51+
res.send(`You are ${name}.\n\nYou asked about ${count} ${word}: ${list}.`);
52+
});
53+
54+
app.listen(PORT, () => {
55+
console.log('Custom server started on port 3000');
56+
});

0 commit comments

Comments
 (0)