API 接口案例

8/9/2022 ES6Node.js

# API 接口案例

# 1. 案例需求

基于 MySQL 数据库 + Express 对外提供用户列表的 API 接口服务。用到的技术点如下:

  • 第三方包 express 和 mysql2

  • ES6 模块化

  • Promise

  • async/await

# 2. 主要的实现步骤

① 搭建项目的基本结构

② 创建基本的服务器

③ 创建 db 数据库操作模块

④ 创建 user_ctrl 业务模块

⑤ 创建 user_router 路由模块

# 3. 搭建项目的基本结构

新建文件夹,然后初始化项目配置文件:

npm init -y
1

① 启用 ES6 模块化支持

  • 在 package.json 中声明 "type": "module"

② 安装第三方依赖包

  • 运行 npm install express@4.17.1 mysql2@2.2.5

# 4. 创建基本的服务器

根目录新建 app.js 作为项目的入口文件,代码如下:

// 使用 ES6 的默认导入语法
import express from 'express'
const app = express()

app.listen(80,()=>{
  console.log('http:127.0.0.1')
})
1
2
3
4
5
6
7

然后 node ./app.js 来启动这个服务器,最简单的服务器就完成了。

# 5. 创建 db 数据库操作模块

import mysql from 'mysql2'

const pool = mysql.createPool({
  host: '127.0.0.1',
  port: 3306,
  database: 'my_db_01',
  user: 'root',
  password: 'admin123',
})

export default pool.promise()

1
2
3
4
5
6
7
8
9
10
11
12

# 6. 创建 user_ctrl 模块

import db from '../db/index.js'

// 使用 ES6 的按需导出语法,将 getAllUser 方法导出出去
export async function getAllUser(req, res) {
  try {
    const [rows] = await db.query('select id, username, nickname, xxx from ev_users')
    res.send({
      status: 0,
      message: '获取用户列表数据成功!',
      data: rows,
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取用户列表数据失败!',
      desc: err.message,
    })
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 7. 创建 user_router 模块

import express from 'express'
import { getAllUser } from '../controller/user_ctrl.js'

const router = new express.Router()
router.get('/user', getAllUser)

export default router

1
2
3
4
5
6
7
8

# 8. 导入并挂载路由模块

import express from 'express'
import userRouter from './router/user_router.js'
const app = express()

app.use('/api', userRouter)

app.listen(80, () => {
  console.log('server running at http://127.0.0.1')
})

1
2
3
4
5
6
7
8
9
10

# 9. 使用 try…catch 捕获异常

import db from '../db/index.js'

// 使用 ES6 的按需导出语法,将 getAllUser 方法导出出去
export async function getAllUser(req, res) {
  try {
    const [rows] = await db.query('select id, username, nickname, xxx from ev_users')
    res.send({
      status: 0,
      message: '获取用户列表数据成功!',
      data: rows,
    })
  } catch (err) {
    res.send({
      status: 1,
      message: '获取用户列表数据失败!',
      desc: err.message,
    })
  }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

如果不捕获异常,那么发生错误的时候,服务器会直接停止。用 try…catch 来捕获错误。

# 总结

ES6 模块化与异步编程总结如下:

① 能够知道如何使用 ES6 的模块化语法

  • 默认导出与默认导入、按需导出与按需导入

② 能够知道如何使用 Promise 解决回调地狱问题

  • promise.then()、promise.catch()

③ 能够使用 async/await 简化 Promise 的调用

  • 方法中用到了 await,则方法需要被 async 修饰

④ 能够说出什么是 EventLoop

  • EventLoop 示意图

⑤ 能够说出宏任务和微任务的执行顺序

  • 在执行下一个宏任务之前,先检查是否有待执行的微任务

具体有忘记的回顾前面几篇文章。