Serving HTML Using Express
Lets discuss how to serve HTML using Express by using an example. In this we will have a Views folder that contains our HTML files. We will use these files to create a home page along with a default 404 page. Lets begin!
First we will begin our project by using terminal to navigate to where you’d like your project to be and creating a folder for it. Do so by entering:
Then you will need to initialize your package.json file using npm. After navigating into your project and firing up your text editor. Open a terminal at the root of your new project and enter:
Once this has completed and you can now see your package.json file lets add express by entering:
npm install --save express
After this has completed we can set up our projects file structure. Please copy the following setup:
Lets go to the top of our app which will coincidentally be app.js. We have covered the basics of what this file should contain previously within my previously mentioned Express blog post. I am going to continue and assume you are familiar most of the contents of this file I’m about to show you. The app.js file should resemble the following (minus the comments):
Now that we have the top of our app squared away lets look at our middleware within the routes folder home.js. Please edit this to resemble the following disregarding the comments:
On line 7 we are importing the contents of path.js lets take a look at this file now to see how it provides us the absolute path to our project. Our path.js file is just 2 lines of code resembling the following:
Now that we have our middleware both written and imported lets go inside home.html and create an html skeleton by typing html and selecting html:5 and hitting enter. Add a link tag and a single h1 tag. The file will then resemble the following:
We can now duplicate this process to create our default error page inside the 404.html file. Also feel free to populate main.css inside the public/css folder with whatever styling you’d like! Once this is complete feel free to spin up your server by entering the following within terminal inside your projects root directory:
At this point if you open a browser and navigate to localhost:3000/home you should see your page!
At this point you should have a working demo capable of serving up a message of “Hello Express World!” for the url of /home along with some css. As well as a default 404 error page for all of the urls that are not found. Now that you have the basic concept of serving whole html files you can expand much further than this simple example. The Express framework is a capable of a lot things outside of this minimal task but hopefully this provides a good foundation to build off of.