Node builds the back-end framework [modular, using MySQL]

This article may be different from the general use of express to build a server with less than 10 lines of code, because I have used springboot to build the back-end framework before, so I feel that although this method is simple, it may lack Extensibility and Normative

0. Project Background

Currently I am developing a small project that I use myself. Since it is a small project and I only use it myself, I feel that there is no need to directly use SpringBoot as the back-end framework, and I hope to get in touch with more things , so choose to use NodeJS as the backend server.

1. Install NodeJS and MySQL

First of all, make sure you have Node and MySQL in your computer, if not, you can refer to the following tutorials

Install Node.js
Install MySQL-5.7.19 (super detailed – graphic tutorial)

2. Create a Node.js project

Open cmd where you need to put the NodeJS backend

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-BIGjDKkD-1679731516961)(assets/image-20230325144650-n69gn7l.png)]

Create a project directory

mkdir your filename

Enter directory

cd your filename

Initialize project

npm init

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-yu0bJc3a-1679731516962)(assets/image-20230325144727-2v432m5.png)]

There is no special requirement, just default to Enter

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-GrS5zpr0-1679731516963)(assets/image-20230325144818-9lm7yss.png)]

3. Install necessary modules

Open the folder just created through vscode and install the following modules

  • express: A popular web framework for building web servers and handling HTTP requests.
  • mysql2: a Node.js driver for MySQL, used to connect and operate MySQL database.
  • dotenv: A module for loading environment variables from .env files, which can help you securely manage sensitive information, such as database passwords.

You can install these modules with the following commands:

npm install express mysql2 dotenv forwarded

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-fzJ3OLMz-1679731516963)(assets/image-20230325145000-j1v7c2c.png)]

The installation here may be affected by the system agent (magic), so please turn off the magic first before installing

Wait for the installation to succeed

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-yUf5bDnE-1679731516963)(assets/image-20230325145558-veas19r.png)]

4. Create HTTP server

Create a index.js file in the root directory

Creating an HTTP server using the express module is very simple, you just need to write the following code:

const express = require('express');
const app = express();

app.get('/', (req, res) => {<!-- -->
  res. send('Hello, world!');
});

app.listen(3000, () => {<!-- -->
  console.log('Server is running on port 3000');
});

Start server

node index.js

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-vSgYu5d7-1679731516963)(assets/image-20230325150205-4823l29.png)]

This code creates an HTTP server listening on localhost:3000. When you visit http://localhost:3000 in your browser, you will see a page that says “Hello, world!”.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-ntNvnilH-1679731516964)(assets/image-20230325150220-njvwhv4.png)]

5. Connect to MySQL database (service)

Create a database

First of all, you need to create a database that you need to use later, you can use tools such as workbench or sqlserver

create database database name

Create a .env file to configure mysql

DB_HOST=localhost
DB_USER=root
DB_PASSWORD=your password
DB_NAME=The name of the database

Create directories service and index.js

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-o2rioPc1-1679731516964)(assets/image-20230325151256-c7et4i4.png)]

Edit index.js

Connecting to a MySQL database is also easy using the mysql2 module. You just need to write the following code:

const mysql = require('mysql2/promise');
require('dotenv').config();

const pool = mysql.createPool({<!-- -->
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME
});

module.exports = pool;

6. Create routing and controller

The route here is not the route of our front-end page, but a route corresponding to a request address

Create a directory

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-6qwnmd6S-1679731516964)(assets/image-20230325160355-j3394x0.png)]

Create a data table

Create a table to test whether it is connected to the database

const pool = require("../../service/index")

async function createTimeTable(req, res) {<!-- -->
    try {<!-- -->
        await pool. query(`
        CREATE TABLE IF NOT EXISTS time_record (
          id INT AUTO_INCREMENT PRIMARY KEY,
          time date NOT NULL,
          name VARCHAR(255) NOT NULL,
          tag VARCHAR(255) NOT NULL,
          duration smallint NOT NULL
        )
      `);

        res.status(200).send('Time table created successfully!');
    } catch (error) {<!-- -->
        console.error('Error creating time table:', error);
        res.status(500).send('Failed to create time table');
    }
}

module.exports = {<!-- -->
    createTimeTable,
}

Create a router correspondence

const express = require('express');
const router = express. Router();
const timeController = require('./time');

router.get('/create', timeController.createTimeTable)

module.exports = router

7. Start the server

Modify index.js

const express = require('express');
const app = express();
const routes = require('./controller/router');
require('dotenv').config();

app.use(express.json());
app. use(routes);

const port = process.env.PORT || 3000;
app.listen(port, () => {<!-- -->
    console.log(`Server is running on port ${<!-- -->port}`);
});

Access address localhost:3000/create

The create here corresponds to the previously set route

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-jYhG3LjD-1679731516964)(assets/image-20230325154909-nfoetcb.png)]

Created successfully

Let’s go to the workbench to see

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture directly Upload (img-SPjI9WRu-1679731516965)(assets/image-20230325154940-2mtvojw.png)]

It exists! Prove that the whole is ok

At present, the overall framework is simply set up, and we will need to fill in each module and implement business logic in the future