Skip to content

Commit 949bd63

Browse files
committed
Implemented the middlewares to handle extracting user data in express
1 parent 16ace89 commit 949bd63

635 files changed

Lines changed: 72914 additions & 0 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

middleware.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// ...existing code...
2+
const express = require('express');
3+
// ...existing code...
4+
const app = express();
5+
6+
app.use(express.json());
7+
8+
const userdata = [];
9+
const info = [];
10+
11+
const usernameValidator = (req, res, next) => {
12+
const username = req.headers['x-username'];
13+
userdata.push(username);
14+
15+
const userInfo = `You are authenticated as ${username}`;
16+
17+
console.log('req.body =', req.body); // debug
18+
19+
let userMessage = 'No subjects requested';
20+
if (Array.isArray(req.body) && req.body.length > 0) {
21+
info.push(...req.body); // push items first
22+
userMessage = `You have requested information about ${req.body.length} subjects: ${req.body.join(', ')}`;
23+
}
24+
25+
console.log(info);
26+
27+
console.log(`
28+
${userInfo}
29+
${userMessage}
30+
`);
31+
32+
next();
33+
}
34+
35+
app.use(usernameValidator);
36+
37+
app.post('/', (req, res) => {
38+
const username = req.headers['x-username']; // use lowercase key
39+
res.send(`Username is ${username}, Subjects: ${JSON.stringify(info)}`);
40+
});
41+
42+
app.listen(3000, () => {
43+
console.log('Server listening on port 3000');
44+
})
45+
// ...existing code...

0 commit comments

Comments
 (0)