简单的API接口案例

API接口案例

基于MySQL数据库 + Express对外提供用户列表的API接口服务

  1. 技术栈:
    • 第三方包express、mysql2
    • ES6模块化
    • Promise
    • async/await
  2. 主要实现步骤
    1. 搭建项目的基本结构
    2. 创建基本的服务器
    3. 创建db数据库操作模块
    4. 创建user_ctrl 业务模块
    5. 创建user_router路由模块

实现

  1. 初始化包管理配置文件package.json —— npm init -y

  2. 启用ES6模块化支持

    • 在package.json中声明"type": "module"
  3. 安装第三方依赖包

    • 运行npm install express@4.17.1 mysql2@2.2.5
  4. 创建最基本的web服务器

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // app.js
    //导入express模块
    import express from 'express'
    //创建express服务器实例
    const app = express()

    //调用app.listen方法,指定端口号并启动web服务器
    app.listen(8080,()=>{
    console.log('Express server running at http://127.0.0.1:8080')
    })
  5. 创建db数据库操作模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // db/index.js
    import mysql from 'mysql2'

    const pool = mysql.createPool({
    host: '127.0.0.1', // 指定操作哪台电脑
    port: 3306, // 指定端口号,一般mysql数据库的端口号都是3306
    database: 'my_db_01',
    user: 'root',
    password: 'ayu123+'
    })

    // 如果导出pool,它不支持以promise API的形式来操作数据库
    // 此时我们需要调用pool提供的.promise(),把返回值导出出去
    // 外界拿到数据库的连接对象之后,就可以以Promise的方式来操作数据库
    export default pool.promise()
  6. 创建user_ctrl 业务模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    // controller/user_ctrl.js
    import db from '../db/index.js'

    // 使用ES6的按需导出语法,将getALLUser语法导出出去
    export async function getAllUser(req,res){
    // 数组中,索引为0的那一项,是最终需要的数据,所以解构赋值出一个rows
    const [rows] = await db.query('select id,username,nickname from users')
    res.send({
    status: 0,
    messages: '获取用户列表数据成功!',
    data: rows,
    })
    }
  7. 创建user_router路由模块

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // router/user_router.js
    import express from 'express'
    import { getAllUser } from '../controller/user_ctrl.js'

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

    export default router

    // 在app.js注册路由
    import userRouter from './router/user_router.js'
    app.use('/api', userRouter)
  8. 使用try…catch捕获异常
    当报错之后,使用catch进行处理,程序不会发生崩溃

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    // controller/user_ctrl.js
    import db from '../db/index.js'

    // 使用ES6的按需导出语法,将getALLUser语法导出出去
    export async function getAllUser(req,res){
    // 数组中,索引为0的那一项,是最终需要的数据,所以解构赋值出一个rows
    try{
    const [rows] = await db.query('select id,username,nickname,xxx from users')
    res.send({
    status: 0,
    messages: '获取用户列表数据成功!',
    data: rows,
    })
    }catch(err){
    res.send({
    status: 1,
    messages: '获取用户数据失败!',
    desc: err.messages
    })
    }
    }