Create a movie reviews app with Node.js and Express

Part 6 - Create a form

Build web apps with NodeJS & Express

🕑 This lesson will take about 20 minutes

In this lesson, we will create a route and a web page template that will be responsible for adding new movies to the database. On the web page, we will have a form where users can enter the movie title, director, genre, review and other information. At this stage, any user will be able to add data to the database but you could add a login system or a moderation system later on.

We will need to create a template for the form as well as two routes:

  • One route will take a GET request for the page that will display the form. This will be the app.get('/add') route.

  • A second route will take a POST request to submit data from the form and save it to the database. This will be the app.post('/add') route.

Let's first create the route for the GET request for '/add' so that we can display the page with the form to users. Add the following block of code to your index.js file (make sure it is above the app.listen() function):

// Show the 'add movie' form

app.get('/add', (req, res) => {
res.render('add');
});

We will also need to add HTML code to create a form in the add.ejs template file (in the views directory/folder). This code will add text boxes so the user can input data about a movie. Each text input has a name eg. "title" or "genre". Notice that the form method is "post" and the action is "/add", so when the form is submitted, a POST request will be made with the '/add' route which will handle the form data and save it to the database.

Add the following HTML code to the add.ejs template file in the views directory/folder:

Restart the server and click on the "Add new movie" button on the home page. It should look like this:

Screenshot showing a web page form for inputting details about a movie

In the next lesson, we will add the code to handle POST requests for the "/add" page so that form data submitted by the user can be collected and added to the database.

Next lesson: Create a movie reviews app (Part 7 - Add data to the database)