leiwuhen-67's blog leiwuhen-67's blog
首页
    • 《Vue》笔记
    • 《React》笔记
    • 《NodeJs》笔记
    • 《CSS》笔记
    • 《Redis》笔记
    • 基础入门
    • 《Mock》笔记
    • 《MySQL》笔记
    • 《Git》相关
影音视听
收藏
关于
GitHub (opens new window)

我的公众号

首页
    • 《Vue》笔记
    • 《React》笔记
    • 《NodeJs》笔记
    • 《CSS》笔记
    • 《Redis》笔记
    • 基础入门
    • 《Mock》笔记
    • 《MySQL》笔记
    • 《Git》相关
影音视听
收藏
关于
GitHub (opens new window)
  • Express

    • 使用Express搭建服务器
    • Express连接数据库MySQL
      • Express之get请求与post请求
      • Node多环境配置(开发环境、生产环境)
    • Koa

    • Egg

    • Node相关

    • 《NodeJs》笔记
    • Express
    心欲无痕
    2022-04-14
    目录

    Express连接数据库MySQL

    假设已创建好名字为 runoob,表为 runoob_tbl 的数据库。

    # 1、安装 mysql

    npm install mysql
    
    1

    # 2、数据库基础配置

    在 db/dbConfig.js 文件中存放 mysql 数据库基础配置,代码如下

    const mysql = {
        host: 'localhost',     // 主机名
        port: '3306',          // 数据库端口号,默认3306
        user: 'root',          // 创建数据库时设置用户名
        password: '12345678',  // 创建数据库时设置的密码
        database: 'runoob',    // 创建的数据库
        connectTimeout: 5000,   // 连接超时
    }
    
    module.exports = mysql
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    # 3、连接数据库、读取数据库工具函数封装

    在 utils/index.js 文件中封装工具函数,连接数据库,读取数据库数据等操作。代码如下:

    const mysql = require('mysql');
    const config = require('../db/dbConfig');
    
    // 连接mysql
    function connect() {
        const { host, user, password, database } = config;
        return mysql.createConnection({
            host,
            user,
            password,
            database
        })
    }
    
    // 新建查询连接
    function querySql(sql) {
        const conn = connect();
        return new Promise((resolve, reject) => {
            try {
                conn.query(sql, (err, res) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(res);
                    }
                })
            } catch (e) {
                reject(e);
            } finally {
                // 释放连接
                conn.end();
            }
        })
    }
    
    // 查询一条语句
    function queryOne(sql) {
        return new Promise((resolve, reject) => {
            querySql(sql).then(res => {
                console.log('res===',res)
                if (res && res.length > 0) {
                    resolve(res[0]);
                } else {
                    resolve(null);
                }
            }).catch(err => {
                reject(err);
            })
        })
    }
    
    module.exports = {
        querySql,
        queryOne
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55

    # 4、业务逻辑处理

    在 services/userService.js 中进行业务逻辑处理,比如读取数据库数据,代码如下:

    const { querySql, queryOne } = require('../utils/index');
    
    // 登录
    function getData (req, res) {
        const query = `select * from runoob_tbl`
        querySql(query).then(resp => {
            let list = [...resp]
            res.json({
                msg: '成功',
                data: list
            })
        })
    }
    
    module.exports = {
        getData
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    # 5、路由模块处理

    在 services/api.js 中进行路由模块处理,代码如下:

    const express = require('express');
    const router = express.Router();
    const service = require('./userService')
    
    router.get('/getData', service.getData)
    
    module.exports = router;
    
    1
    2
    3
    4
    5
    6
    7

    # 6、根目录 index.js 文件中代码修改

    const express = require('express')
    const app = express()
    const port = 3010
    
    const apiRouter = require('./services/api')
    
    // 全局中间件
    app.use((request, response, next) => {
        response.header('Access-Control-Allow-Origin', '*')
        next()
    })
    
    // 1. 使用中间件,会自动加入req.body属性,这个属性中就包含了post请求所传入的参数
    app.use(express.urlencoded());
    
    //请求体中的携带的复杂json格式数据解析出来,保存在req.body中
    app.use(express.json());
    
    // 静态文件管理,如图片、css样式等。
    app.use(express.static('public'))
    
    app.use('/api', apiRouter)
    
    // 404处理
    app.use('*', (req, res) => {
        res.status(404).render('404', {url: req.originalUrl})
    })
    
    // 500处理
    app.use((err, req, res, next) => {
        res.status(500).render('500')
    })
    
    app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
    })
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36

    现在我们访问 localhost:3010/api/getData 就能获取到数据库中的数据了,例如:

    如果要对上面的日期进行格式化,可以使用 moment.js。

    安装 moment.js

    npm install moment
    
    1

    在 utils/dateFormat.js 文件中封装代码如下:

    const moment = require('moment');
    
    function dateFormat(date, format) {
        return moment(date).format(format)
    }
    
    module.exports = {
        dateFormat
    }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    然后在 services/userService.js 文件中更改代码如下:

    const { querySql, queryOne } = require('../utils/index');
    const {dateFormat} = require('../utils/dataFormat')
    
    // 登录
    function getData (req, res) {
        const query = `select * from runoob_tbl`
        querySql(query).then(resp => {
            resp = resp.map(item => ({
                ...item,
                submission_date: dateFormat(item.submission_date, 'YYYY-MM-DD HH:mm:ss')
            }))
            let list = [...resp]
            res.json({
                msg: '成功',
                data: list
            })
        })
    }
    
    module.exports = {
        getData
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22

    现在效果如下:

    ps:在连接数据库时可能会报这个错误:Client does not support authentication protocol requested by server;consider upgrading MySQL client 这种错误。

    这时候可更改加密方式

    mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
    
    mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456';   // 密码可随便改
    
    mysql> FLUSH PRIVILEGES;      // 刷新
    
    1
    2
    3
    4
    5
    编辑 (opens new window)
    上次更新: 7/2/2024, 11:06:45 AM
    使用Express搭建服务器
    Express之get请求与post请求

    ← 使用Express搭建服务器 Express之get请求与post请求→

    Theme by Vdoing
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式