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
andNormative
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
Create a project directory
mkdir your filename
Enter directory
cd your filename
Initialize project
npm init
There is no special requirement, just default to Enter
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
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
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
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!”.
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
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
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
Created successfully
Let’s go to the workbench to see
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