node+express build mall project (2-operate Mysql to complete the registration account interface)
- Today we use express and mysql plugin to complete the operation of the mysql database
- Now start to install the database plug-in
npm install mysql --save-dev
- After the installation is complete, start to configure the database.
- Create a new model folder in the outer directory, create a new db.js file
- In the db file, we configure the basic configuration of the link database
- There are also friends who have not installed mysql, please install it first. The blogger’s version is above 8.
var mysql = require('mysql'); //导入 mysql 模块
let dbConfig = {
host: 'localhost', // ip
port: '3306', // 端口号
user: 'root', // 账户
password: 'as946640', // 密码
database: 'shopmall' // 数据库名称
}
- Save and then we write a query function and export the function
- The blogger here uses Promise to encapsulate more easily and clearly
module.exports = {
query: function (sql, params, callback) {
//每次使用的时候需要创建链接,数据操作完成之后要关闭连接
var connection = mysql.createConnection(dbConfig)
// 封装 Promoise 返回结果
return new Promise((resolve, reject) => {
connection.connect((err) => {
// 返回错误
if (err) reject(err)
// 执行查询
connection.query(sql, params, (err, rows) => {
if (err) reject(err)
// 释放连接,否则会卡顿
connection.end((err) => {
if (err) reject(err)
})
// 返回结果
resolve(rows)
})
})
})
}
};
- Next comes our topic. Create a new user module in the router file to handle the user interface.
- Next enter the topic to write our user module user registration interface
- First, we first introduce db file operation data and express and then instantiate routing
var express = require('express');
var router = express.Router();
const db = require('./../../model/db.js')
Finally write our registration interface and export
/* 注册用户. */
router.post('/register', async (req, res) => {
const {
userName,
password
} = await req.body; // 获取 用户产地来的数据
// 新建 插入 sql
const sql = `INSERT INTO user (userName,password) VALUES ( '${
userName}','${
password}')`
try {
// 执行 sql查询函数 返回结果
let blogs = await db.query(sql)
if (blogs) {
res.json({
code: 200,
msg: '注册成功'
})
}
} catch (error) {
// 错误处理
res.json({
code: 500,
msg: error.sqlMessage
})
}
});
module.exports = router;
- Friends, remember to mount the current user.js routing file in the entry file app.js
var usersRouter = require('./routes/user/users');
app.use('/users', usersRouter);
- Now we are doing interface testing. The blogger uses ApiPost here. Domestically produced is still very powerful.
- Finally, the database looks at the data we registered
- Found that our registered data has been submitted to the database