If you have been following along with our series on how to create your own web server, you should now be familiar with node.js and Express. Node.js lays the groundwork for the web server and Express builds upon it. If you haven’t already, I recommend that you take a look at the previous blog posts on Node.js and Express before we get started.
This use statement means that when you visit your project in a web browser, Express will look in the routes folder for a file called index.js that will tell the browser what to do. Right now, the index.js file should look something like this:
Right now, the Express router has one interaction that will render the home page. Currently, when there is a GET request to the route ‘/‘, Express will render the view found in views/index.ejs. The first argument for the render function is the name of the view file, and the second is an object that will be passed to the view file when it is rendered. This object can be used by EJS to change what is rendered on the page, without having to write an entirely new view. Right now the view will only render two lines of text. We are going to expand on this in order to show some dynamic content in the browser.
Rendering with EJS
We simply add a new property to the object we are sending to the render function. The property items is an array containing three strings. Now we will print these strings in our EJS file.
We create a for loop that will iterate through the array we passed from our Express function. The loop is places inside <% %> tags because we do not want the for loop itself to be added to the web page. Inside the loop, we have a <li> tag that will place an item on the web page for each item in the array. To display the item from the array, use the tag <%= items[i] %>. This will look up the element in the items, array, and add it to the web page. As you can see, these tags can be place anywhere inside normal html. To view these changes, just restart the server and reload the page in your browser. You should see something like this: