Express
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.
-
ExpressRequest, Response
Express is built on top of Node’s networking concepts, leveraging the power of the
HTTPserver we have been using, and the existingRequestandResponsetypes. We’ll take some time to learn more about howRequestandResponsework. -
ExpressEXERCISE: A JSON API resource
Build a set of Express request handlers for creating, listing, updating and destroying a “course” resource.
-
ExpressViews
Modern versions of Express leave the job of “views” — HTML generation from declarative templates — up to other libraries. We’ll look at one of the most common view libraries, which allows us to express HTML using Handlebars.js. We’ll be sure to cover topics like layouts, handlebars helper functions, and passing data from our javascript into a template.
-
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.
-
ExpressRouting
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, andhttp://localhost:3000/api/coursesprovides a JSON response. -
ExpressMiddlewares
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, theOriginheader should be validated against theallowedOriginslist, and if everything checks out the appropriate CORS response headers should be set on theresponseobject.