Exercise: Building an Express.js Server
Use what you've learned in this chapter to complete this coding exercise.
We'll cover the following
Problem statement
The web application relies heavily on its server. Whenever a client sends a request, the server plays a vital role in processing it. In this exercise, your objective is to create a server using Express.js to set up the fundamental structure of a web application. This server should excel in handling API requests and rendering HTML pages. The detailed project specifications are outlined below.
API routing
Create an API route named
/api/hello
that returns a JSON response.Ensure that the API route is correctly configured to handle HTTP requests.
This route is typically used for serving API data. You can choose any message you want to include in the JSON response.
Express middleware
Implement Express middleware for error handling.
Create a middleware to handle server-side errors and respond with a
500
status code and an error message.Create a custom error page named
500.html
to manage server errors. If your application faces an internal error, this page should handle the situation gracefully and present a message500 - Server-side Error Occurred
.Implement a middleware to handle
404
errors and respond with a404
status code and a404 - Page Not Found
message.You should create a custom
404.html
error page that will be used in the event that a user navigates to a route that doesn’t exist in your application. This page should inform the user that the requested page was not found and may include a message or options for navigating back or to other parts of the application.
Server initialization
Create an HTTP server using
express()
to serve your Express.js application.Ensure the server listens on the port
3000
and logs a message to the console when it’s ready.Establish error handling within the
server.js
file, and specify how the server should react when encountering errors or404
situations.Set up error handling in the
server.js
file, and define the server’s response when it encounters internal server errors (HTTP500
).
Try it yourself
Click the “Run” button below to execute the code. Once the execution is completed, observe the output by navigating to the link provided at the bottom of the playground.
Get hands-on with 1400+ tech skills courses.