|
| 1 | +import express from 'express'; |
| 2 | +const app = express(); |
| 3 | + |
| 4 | +// Built-in middleware to parse JSON bodies |
| 5 | +app.use(express.json()); |
| 6 | + |
| 7 | +// Middleware 1: Extract username from header or set to null |
| 8 | +function usernameMiddleware(req, res, next) { |
| 9 | + const username = req.header('X-Username'); |
| 10 | + req.username = username || null; |
| 11 | + next(); |
| 12 | +} |
| 13 | + |
| 14 | +app.post('/info', usernameMiddleware, function(req, res) { |
| 15 | + // req.body is now automatically parsed by express.json() |
| 16 | + if ( |
| 17 | + !Array.isArray(req.body) || |
| 18 | + !req.body.every(function(item) { return typeof item === 'string'; }) |
| 19 | + ) { |
| 20 | + return res.status(400).send('Invalid body: must be JSON array of strings'); |
| 21 | + } |
| 22 | + |
| 23 | + const authMessage = req.username |
| 24 | + ? 'You are authenticated as ' + req.username + '.' |
| 25 | + : 'You are not authenticated.'; |
| 26 | + |
| 27 | + const count = req.body.length; |
| 28 | + const subjects = req.body.join(', '); |
| 29 | + const subjectWord = count === 1 ? 'subject' : 'subjects'; |
| 30 | + const subjectMessage = count |
| 31 | + ? 'You have requested information about ' + count + ' ' + subjectWord + ': ' + subjects + '.' |
| 32 | + : 'You have requested information about 0 subjects.'; |
| 33 | + |
| 34 | + res.send(authMessage + '\n\n' + subjectMessage); |
| 35 | +}); |
| 36 | + |
| 37 | +const PORT = 3000; |
| 38 | +app.listen(PORT, function() { |
| 39 | + console.log('Server running on http://localhost:' + PORT); |
| 40 | +}); |
0 commit comments