mf

Build Web Applications Using Node.js

Introduction

Aside from building APIs, Node.js is great for building standard web applications. It has powerful tools to meet the taste of web developers. In this tutorial, you will be building a web application that can serve as a local library. 

While building you will learn about some types of middleware, you will see how to handle form submission in Node.js, and you will also be able to reference two models.

Let’s get started.

Getting Started

Start by installing the express generator on your machine.

Run the express generator command to generate your application.

Now migrate into your working, open package.json, and make the dependencies similar to what I have below.

Run the command to install the packages.

Set Up the Entry File

app.js was created when you ran the generator command; however, you need to set up extra configuration. Edit the file to look like what I have below.

  1. You required the two routes you will be making use of in building this application. You will create the routes file shortly. The required routes are assigned as values to two different variables which are used when setting up the middleware for your routes.
  2. You set Mongoose to use global.Promise. The variable MongoDB is assigned the MONGODB_URI of your environment or the path to your local mongo server. This variable is passed as an argument to connect to the running MongoDB server.
  3. You set up session middleware using express-session. This middleware is important as you will be displaying flash messages in some parts of your application.
  4. You set up middleware for validation. This middleware will be used to validate form input, ensuring that users of the application do not submit an empty form. The validation uses a package installed, express-validator.
  5. You set up middleware which will come in handy when displaying flash messages. This middleware makes use of connect-flash.
  6. The routes for the application are set up to make use of the routes file you required. Requests pointing to /genres and /books will make use of the genres and books routes files respectively. At this moment you have not created the routes files, but you will do that soon.

Book and Genre Model

The Book Model will make use of Mongoose Schema to define how the books will be structured. Create a directory called models, and a new file called Book.js. Here is what it looks like.

Here you have four fields. The last field is used to store the genre each book belongs to. The genre field here references the Genre model, which will be created next. That’s why the type is set to Schema.Types.ObjectId, which is where the ids of each referenced genre will be saved. ref specifies the model you are referencing. Note that genre is saved as an array, meaning that a book can have more than one genre.

Let’s go ahead a create the Genre model.

For your Genre, you need just one field: name.

Genre Index Route and View

For this tutorial, you will make use of two routes paths for your genre: a path to add new genres, and another that lists the genres you have. Create a file in your routes directory called genres.js.

Start by requiring all the modules you will be making use of.

Next, drop in the route that handles the index file for your genres.

This route gets called whenever requests are made to /genres. Here you call the find method on your Genre model to obtain all the genres that have been created. These genres are then rendered on a template called genres. Let’s go ahead and create that, but first, update your layout.pug to look like this:

This will give your views a nice structure to aid navigation. Now create a view file called genre.pug. In this file, you will loop through the genres created and output each genre in an unordered list.

Here is how the file should look.

Add New Genre Routes and View

Go back to your routes/genres.js to add the routes that will handle the creation of new genres.

  1. The job of this router is to simply display the page for adding new routes. This router gets called whenever requests are made to /genres/add path.
  2. This router handles the submission of the form. When the form is submitted, we check to ensure that a name is entered by the user. If no name is entered, the page is re-rendered. If the checks are good to go, the genre is saved and the user is redirected to the /genres page.
  3. The module is exported as a router.

Now you can go ahead and create the page for adding a new genre.

Books Routes and View

Create a new route file for books, and name it books.js. As you did earlier with the genre, start by requiring the necessary modules.

Next, set up the router for displaying all the books saved in the library. Try that on your own in the way as you set up that of the genre; you can always check back to make corrections.

I guess you tried that out—here is how it should look.

When this router is called, a request is made to find all books saved in the database. If all goes well, the books are shown on the /books page, else an error is thrown.

You need to create a new file for displaying all books, and here is how it should look.

You simply loop through the books returned and output the name and description of each book using an unordered list. The name of the book points to the individual page of the book.

Add New Book Routes and View

The next router you set up will handle the addition of new books. Two routers will be used here: one will simply render the page, and another will handle the submission of the form.

This is how the routers look.

In the first router, you are displaying the /addBooks page. This router is called when a request is made to /add path. Since books added are supposed to have genres, you want to display the genres that have been saved to the database.

The code above finds all the genres in your database and returns them in the variable genres. With this, you will be able to loop through the genres and display them as checkboxes.

The second router handles the submission of the form. First, you check the body of the request to ensure that some fields are not empty. This is where the express-validator middleware you set in app.js comes handy. If there are errors, the page is re-rendered. If there are none, the new Book instance is saved and the user is redirected to the /books page.

Let’s go ahead and create the views for this.

Create a new view file called addBooks.pug. Note that the name of the view matches the first parameter given to res.render. This is because you are rendering a template. During redirection, you simply pass the path you want to redirect to, as you did with res.redirect('/books').

Having established that, here is what the views should look like.

The important thing to note here is the form action and method. When the submit button is clicked, you are making a POST request to /books/add. One other thing—once again you loop through the collection of genres returned and display each of them.

Book Show Route and View

Let us drop in the route to handle the requests made to each books page. While you are there, it is important to export your module too.

No magic is happening here.

First, requests made to this router must have an id: the id of the book. This id is obtained from the params of the request using req.params.id. This is used to identify the specific book that should be obtained from the database, as the ids are unique. When the book is found, the genre value of the book is populated with all the genres that have been saved to this book instance. If all goes well, the book view is rendered, else an error is thrown.

Let’s create the view for a book. Here is how it should look.

You can start up your node server by running:

Conclusion

Now you know how to build a standard web application in Node.js, not just a simple to-do app. You were able to handle form submission, reference two models, and set up some middleware.

You can go further by extending the application—try adding the ability to delete a book. First add a button to the show page, and then go to the routes files and add a router for this. Note that this is going to be a POST request.

You can also think of more features to add to the application. I hope you enjoyed it.

Powered by WPeMatico

Leave a Comment

Scroll to Top