Course Resources

Search

Search IconIcon to open search

Last updated Unknown

# Paired Program: Mini Blog with Database

# Objective

Your task is to enhance the mini blog app by replacing the in-memory array with a database. This will allow blog entries to persist beyond the server session, making the app more practical for real-world use.

# Requirements

You will need to have your database and MySQL Workbench installed and have completed the first mini blog app. You’ll be connecting to a database to store and retrieve data instead of using an array.

# Setup

Database Setup:

Connect to MariaDB:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Import the MariaDB Package
const mariadb = require('mariadb');

// Configure the database connection
const pool = mariadb.createPool({
    host: 'localhost',
    user: 'root',
    password: '1234',
    database: 'miniblog'
});

// Function for connecting to the database
async function connect() {
    try {
        let conn = await pool.getConnection();
        console.log('Connected to the database');
        return conn;
    } catch (err) {
        console.log('Error connecting to the database: ' + err);
    }
}


## Update the Form Submission Route

Convert the /submit Route to Save Data in the Database:

Return to the Form:

# Backend Validation

Prevent Submission of Invalid Posts: To ensure data integrity, implement the following validation logic in your /submit POST route before inserting the data into the database:

Remove leading or trailing whitespace:

1
data.firstName.trim()

Show an error message on the frontend: Send the user back to the home page along with any error messages from the backend.

Make the Form Sticky: Retain user-entered data in the form fields after any backend validation errors.

You will need to pass both the form data and the errors to the home page from your /submit route:

1
res.render('home', { data: data, errors: errors });

# Retrieve All Posts from the Database

Set Up the /entries Route:

Render the Posts in EJS:

Test the App: