Task 1: Basic Server Setup
Create a new Express server with:
- CORS middleware enabled
express.json()middleware- A simple logging middleware that shows timestamp, method, and URL
- At least 3 GET routes that return different data
- 404 handler
- Error handling middleware
Task 2: Authentication Middleware
Create your own authentication middleware function that:
- Checks for an
Authorizationheader in incoming requests - Validates that the token is
Bearer letmein - Returns appropriate error responses for missing or invalid tokens
- Allows valid requests to continue to the route handler
Create these routes:
GET /→ returns{ message: "Public page" }(no auth)GET /protected→ usescheckAuth, returns{ message: "Protected page" }GET /admin→ also usescheckAuth, returns{ message: "Admin dashboard" }
Test cases:
/→ works without headers/protectedor/admin:- No header → 401
- Wrong token → 403
- Token
Bearer letmein→ works
Task 3: Request Counter Middleware
Create a middleware that counts how many requests have been made to your server. Your middleware should:
- Keep track of the total number of requests (start at 0)
- Increment the counter for each request
- Add a header to the response called
X-Request-Countwith the current count - Log the count with each request:
Request #5 - GET /users - Also return the counter value in the JSON response body.
Hint: Declare your counter variable (like let count = 0) outside the middleware function so it persists across requests.
Apply this middleware to all routes and test with multiple requests to see the counter increase.