Create a movie reviews app with Node.js and Express
Part 2 - Connecting the app to the database
Build web apps with NodeJS & Express
🕑 This lesson will take about 30 minutes
Step 1 - Connect your app to a database
The next step is to tell our project that we will be using the SQLite engine for our database. Node.js has a package called sqlite3 that we can use to connect to and manage a database. If you didn’t already do this in the previous step, you will need to install the sqlite3 package using the terminal command npm i sqlite3 (this was covered in the previous lesson).
Create a new file for your web server in the main folder/directory for your project called index.js - this will contain all of the code for connecting to and managing the database as well as handling all the different requests and responses from/to users. In this file, we will have use the line const sqlite3 = require('sqlite3').verbose(); to tell the app that we are using the sqlite3 package we installed earlier. Then we add a block of code that will be responsible for making a connection to the database.
Add the following code to the index.js file in your project’s main folder/directory:
Make sure you save your index.js file and then run the node index.js command in your terminal to start the server and check that your database is connected to the app.
Now that your database is connected, you will notice a new file called mydb.db has appeared in your project’s main folder/directory - don’t delete or edit this file as it will contain the data in your database.
Now that your app is connected to the database, you can start to define the type of information it will store and start adding some data to the database.
Next lesson: Create a Movie Reviews App (Part 3 - Create a table and add data to the database)