Express is, by a fairly large margin, the most popular web application framework for Node.js. It can be used to respond to HTTP requests with JSON, HTML, or pretty much anything else.
Express is built on top of Node’s networking concepts, leveraging the power of the
HTTPserver we have been using, and the existing
Responsetypes. We’ll take some time to learn more about how
ExpressEXERCISE: A JSON API resource
Build a set of Express request handlers for creating, listing, updating and destroying a “course” resource.
ExpressEXERCISE: Course as HTML
Build a set of new routes for CRUD (Create, Read, Update, Delete) operations on the same course object we modeled in the last exercise — but render responses as HTML instead of JSON.
Once we start responding to a variety of URLs, we’ll want to start breaking our code up into independent modules. Each module should follow SRP (Single Responsibility Principle) for handling a specific concern, or set of closely-related concerns.
ExpressEXERCISE: JSON + HTML
Time for us to combine HTML and JSON. Use hierarchical routing to expose both of the last two exercises, such that:
http://localhost:3000/coursesprovides an HTML response, and
http://localhost:3000/api/coursesprovides a JSON response.
Middlewares are modular request/response handling units that can be composed together in a server. You could have one middleware that ensures requests are coming from only a specified origin; one that parses the body (text) into JSON for later use; one that logs the amount of time it took to generate a response; and more! We’ll build a few middlewares together, and try applying them broadly across our whole app, as well as specifically to a family of routes (or a single route).
ExpressEXERCISE: CORS headers
Build an Express middleware for CORS (Cross-Origin Resource Sharing) validation. When an incoming
requestis received, the
Originheader should be validated against the
allowedOriginslist, and if everything checks out the appropriate CORS response headers should be set on the