1. 程式人生 > 其它 >API介面案例

API介面案例

案列需求

基於MYSQL資料庫+Express對外提供使用者列表的API介面服務。用到的技術點如下:

  • 第三方的包express和mysql2
  • ES6模組化
  • Promise
  • async/await

主要的實現步驟

  1. 搭建專案的基本結構
  2. 建立基本的伺服器
  3. 建立db資料庫操作模組
  4. 建立user_ctrl業務模組
  5. 建立user_router路由模組

搭建專案的基本結構

  1. 啟用ES6模組化的支援

            在package.json中宣告“type”:“moudle”

         2. ’安裝第三方依賴包

              執行 npm i express mysql

     

 建立基本的伺服器

// 使用ES6的預設匯入語法
import express from "express";
const app = express();
app.listen(80,()=> {
    console.log(`伺服器已啟動在http://127.0.0.1`);
})

  

  

建立db資料庫操作模組

import mysql from 'mysql'

const pool = mysql.createPool({
    host: '127.0.0.1', 
    port: 3306,
    database:'my_db_01', // 請填寫操作資料庫的名稱
    user: 'root',//請填寫登入資料庫的使用者名稱
    password: 'admin123'//請填寫登入資料庫的密碼
})

// 預設匯出一個支援Promise API的pool
export default pool.promise()

  

建立user_ctrl業務模組

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

// 獲取所有的使用者的列表資料
// 使用ES6的按需匯出的語法,將getAllUser方法匯出
export async function getAllUser(req, res) {
    // db.query() 函式的返回值是Promise的例項物件,因此可以使用async/await進行簡化
    const [rows] = await db.query('select id, username,nickname from ev_users');
    console.log(rows);
    res.send({ // 將獲取到的資料返回給客戶端
        status:0,
        message: '獲取使用者列表資料成功',
        data: rows 
    })
}

建立user_router業務模組 

import express from "express";
// 按需匯入getAllUser函式
import { getAllUser } from "../user_ctrl";
// 建立路由物件
const router = new express.Router()
// 掛載路由規則
router.get('/user', getAllUser);
// 使用ES6的預設匯出語法,將路由物件共享出去
export default router

  

掛載並使用路由模組

import express from "express";
// 按需匯入getAllUser函式
import { getAllUser } from "../user_ctrl";
// 建立路由物件
const router = new express.Router()
// 掛載路由規則
router.get('/user', getAllUser);
// 使用ES6的預設匯出語法,將路由物件共享出去
export default router

  

使用try...catch捕獲異常

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

// 獲取所有的使用者的列表資料
// 使用ES6的按需匯出的語法,將getAllUser方法匯出
export async function getAllUser(req, res) {
    //使用try...catch 捕獲Promise非同步任務中產生的異常錯誤,並在catch塊中進行處理
    try {
        // db.query() 函式的返回值是Promise的例項物件,因此可以使用async/await進行簡化
        const [rows] = await db.query('select id, username,nickname,xxx from ev_users');
        res.send({ // 將獲取到的資料返回給客戶端
            status: 0,
            message: '獲取使用者列表資料成功',
            data: rows
        })

    } catch(e) {
        res.send({ // 將獲取到的資料返回給客戶端
            status: 1,
            message: '獲取使用者列表資料失敗',
            msg: e.message
        })
    }
    
}