Back to main site

Node and Express

This is a continuation of my effort to document my Node learning process. I am still going through this excellent Udemy course and building upon very basic incremental examples to understand how and why Node can do the stuff that it does. In a previous blog post I wrote about how to create Node servers from scratch. This time, I’ll go through a few examples that use Node with Express to set up an app.

What Is Express

Express is a framework to enhance Node and make Node easier to work with. The first example that I went through just created a very basic app using Express, which is shown below. I’ve commented nearly every single line of code in (maybe painful) detail just to really understand what’s happening at every stage. Important things to make note of:

In this example, GET requests to the /form route will serve a static HTML file.

Structuring the App

The next example, we look at a different way of structuring our app to separate routes and make them easier to deal with. Here, we have a folder called controllers in the same directory as app.js and form.htm, and controllers contains apiController.js and htmlController.js. The static file form.htm stays the same and everything that has changed from the previous example is indicated by comments.

Using the Express Router

The next example deals with another way of structuring our app and uses the Router middleware provided by Express. Here, we have a folder called routes in the same directory as app.js, and routes contains index.js and users.js. Both of the routes files return an Express Router object, and then the main app.js file passes those Router objects to its own middleware. This effectively sets up routes with subroutes, where the routes defined in app.js are the main routes and the routes defined in the routes files are the subroutes that can be accessed via the main routes.

These are all definitely just demonstrative examples that don’t do anything terribly exciting, but they helped me to understand how Express works with Node!