File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ const express = require ( "express" ) ;
2+
3+ const app = express ( ) ;
4+ app . use ( express . json ( ) ) ; //built in JSON parser
5+ const PORT = 3000 ;
6+
7+ function usernameMiddleware ( req , res , next ) {
8+ const headerValue = req . header ( "X-Username" ) ; // Express helper for headers
9+ req . username = headerValue ? headerValue : null ;
10+ next ( ) ;
11+ }
12+
13+ app . post ( "/" , usernameMiddleware , ( req , res ) => {
14+ // Validate: must be array of strings
15+ if (
16+ ! Array . isArray ( req . body ) ||
17+ ! req . body . every ( ( x ) => typeof x === "string" )
18+ ) {
19+ return res
20+ . status ( 400 )
21+ . type ( "text" )
22+ . send ( "Invalid body. Expected a JSON array of strings." ) ;
23+ }
24+
25+ const username = req . username ;
26+ const authLine = username
27+ ? `You are authenticated as ${ username } .`
28+ : `You are not authenticated.` ;
29+
30+ const subjects = req . body ; // should be an array of strings
31+ const count = subjects . length ;
32+
33+ let subjectsLine = `You have requested information about ${ count } subject${ count === 1 ? "" : "s" } ` ;
34+ subjectsLine += count > 0 ? `: ${ subjects . join ( ", " ) } .` : `.` ;
35+
36+ res . type ( "text" ) . send ( `${ authLine } \n\n${ subjectsLine } ` ) ;
37+ } ) ;
38+
39+ app . listen ( PORT , ( ) => {
40+ console . log ( `Listening on http://localhost:${ PORT } ` ) ;
41+ } ) ;
You can’t perform that action at this time.
0 commit comments