

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: Welcome to Web Servers
incomplete
2: Async TypeScript
incomplete
3: Setup
incomplete
4: Build
incomplete
5: Server
incomplete
6: Fileservers
incomplete
7: Fileserver Quiz
incomplete
8: Serving Images
incomplete
9: Workflow Tips
incomplete
10: Custom Handlers
incomplete
11: Request, Response
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
In the previous exercise, we used the express.static middleware, which serves static files using a built-in handler.
An HTTP handler in Express is typically a function with the following signature:
(req: Request, res: Response) => Promise<void>;To handle an incoming HTTP request, all a handler function requires is the request object and a response object in order to communicate back to the client.
Let's add a readiness endpoint to the Chirpy server! Readiness endpoints are used by external systems to check if our server is ready to receive traffic.
The endpoint should be accessible at the /healthz path.
The endpoint should simply return a 200 OK status code indicating that it has started up successfully and is listening for traffic. The endpoint should return a Content-Type: text/plain; charset=utf-8 header, and the body will contain a message that simply says "OK" (the text associated with the 200 status code).
Create src/api/readiness.ts and export a handlerReadiness function from it. In src/index.ts, import it from "./api/readiness.js". You can also keep the handler in src/index.ts.
The Express app object has methods matching the HTTP methods. The parameters are the path and the handler function. In src/index.ts, use the .get method to add a handler for the /healthz path.
Import the Express types explicitly: import { Request, Response } from "express";
These are Express's Request/Response objects, which differ from the Fetch API's Response
app.get("/healthz", handlerReadiness);Your handler should use various methods of the response object to do the following:
Express automatically sets the status code to 200. If you want to change it, you can use the .status method.
Now that we've added a new handler, we don't want potential conflicts with the static files handler. Update the static file serving to use the /app/ path instead of /.
To do this:
app.use("/app", express.static("./src/app"));Ensure the server handles requests for both the readiness endpoint and static files correctly.
Run and submit the CLI tests.