Context: you already have the MVC starter shown above. Do not change controllers, schemas, or routes for these tasks.
-
Do not remove existing functionality. You can replace the placeholder app-level middleware if the task tells you to.
-
Put new app-level middleware above
app.use("/api/students", student)and above the 404 handler. -
Do not add new files. Everything stays in
server.jsfor this pair of exercises. -
Test with Postman.
Goal: create a simple app-level middleware that helps you see what is hitting your server.
-
Replace the current placeholder app-level middleware that logs "I am an application level middleware" with a new middleware named
requestSummary. -
It must print to the console: HTTP method, original URL, and an ISO timestamp of when the request arrived. One line per request.
-
It must attach a response header named
X-Request-Receivedwith the same ISO timestamp. -
It must call
next()so that routes continue to work.
- Place
requestSummaryafterapp.use(cors())and beforeapp.use("/api/students", student).
// App-level: request summary logger
function requestSummary(req, res, next) {
// TODO 1: create an ISO timestamp string
// TODO 2: console.log one line with method, originalUrl, and the timestamp
// TODO 3: set a response header named "X-Request-Received" to the timestamp
// TODO 4: call next()
}
// register it here
// app.use(requestSummary);-
A response header is metadata sent before the body. You must set it before
res.send(...)orres.json(...)or the headers will already be locked. -
Do it inside your middleware, then call
next()so the request continues to the route handlers. -
You can use either of these (they behave the same for our use case):
-
res.set(name, value)orres.set({ name: value }) -
res.setHeader(name, value)(Node.js style)
-
-
Header names are case-insensitive. Use a conventional hyphenated form like
X-Request-Received. -
Common mistakes to avoid: forgetting
next(), setting the header after you already sent the response, or trying to setres.headers(that property does not exist).
function requestSummary(req, res, next) {
const ts = new Date().toISOString();
res.set('X-Request-Received', ts); // set the header
console.log(req.method, req.originalUrl, ts);
next();
}GET base URL
-
Open Postman and create a request. Set Method to GET and URL to
http://localhost:5000/. -
Send the request.
-
In the response, open the Headers tab and confirm
X-Request-Receivedis present with an ISO timestamp. -
Check your server console. You should see a single line like
GET / <time>.
POST create student
-
Create a new request. Set Method to POST and URL to
http://localhost:5000/api/students. -
In Headers, add
Content-Type: application/json. -
In Body, select
rawandJSON, then paste:
{
"first_name": "Ada",
"last_name": "Lovelace",
"email": "ada@love.com",
"age": 30
}-
Send the request.
-
Expect Status
201 Createdand theX-Request-Receivedheader in the response. The console should log one line likePOST /api/students <time>.
Goal: level up the previous exercise. Add a guard that can short-circuit requests when maintenance is on, and enhance logging with status code and duration.
-
Performance logger upgrade
-
Start a timer at the moment the request arrives.
-
Use
res.on("finish", ...)to log a single line after the response is sent. -
That log line must include: HTTP method, original URL, status code, and duration in milliseconds.
-
This should replace or upgrade the logger from Exercise 1. You still keep the
X-Request-Receivedheader from Exercise 1.
-
-
Maintenance gate
-
Create a second app-level middleware named
maintenanceGatethat checks an environment variable, for exampleprocess.env.MAINTENANCE_MODE. -
If the value is the string
on, immediately respond with status 503 and a small JSON body like{ msg: "Server under maintenance" }. Do not callnext()in this case. -
If maintenance is not on, call
next().
-
- Register the performance logger first, then the maintenance gate, then your routes. This ensures you still see a completed log line even when the gate blocks requests.
// App-level: performance logger with status and duration
function performanceLogger(req, res, next) {
// TODO 1: capture start time now
// TODO 2: ensure the ISO timestamp header from Exercise 1 is still set
// TODO 3: after response finishes, log method, url, res.statusCode, and elapsed ms
// Hint: use res.on("finish", () => { /* log here */ })
// TODO 4: next()
}
// App-level: maintenance gate
function maintenanceGate(req, res, next) {
// TODO 1: check process.env.MAINTENANCE_MODE
// TODO 2: if it equals "on", send status 503 with a small JSON message and return
// TODO 3: otherwise call next()
}
// register them in this order
// app.use(performanceLogger);
// app.use(maintenanceGate);Turn maintenance on
- Set the environment variable and restart the server (
MAINTENANCE_MODE=on)
Request in Postman
-
Create a GET request to
http://localhost:5000/api/students. -
Send the request. You should see Status
503 Service Unavailablewith a body like:
{ "msg": "Server under maintenance" }- Check the server console. Your performance logger should still print a completed line with method, url, status, and duration.
Turn maintenance off and retest
-
Set the variable to off and restart the server (
MAINTENANCE_MODE=off) -
Send the same GET request in Postman.
-
You should get the normal response (for example,
200 OK), and the console log should include method, url, status, and duration.
-
Exercise 1 prints a clear one line request summary and sets
X-Request-Receivedfor every response. -
Exercise 2 logs method, url, status, and duration using
res.on("finish"). -
Exercise 2 blocks requests with status 503 when
MAINTENANCE_MODE=on. -
Middlewares are registered above the student routes and above the 404 handler.
-
No new files were added and controllers or schemas were not modified.