使用Egg.js編寫RestfulAPI接口(三)編寫Api接口


1.在VsCode編輯器中安裝egg插件,擁有代碼提示功能

2.在controller目錄下創建user.js文件

3.輸入egg可以快速生成controller模板代碼

3.編寫RestfulAPI接口(查詢用戶列表、查詢單個用戶、添加用戶),完整的user.js代碼如下

'use strict';

const Controller = require('egg').Controller;

// 模擬用戶存儲
const userList = [];

class UserController extends Controller {
    // 查詢用戶列表
    async list() {
        this.ctx.body = {
            msg: 'ok',
            data: userList
        }
    }

    // 查詢單個用戶
    async detail() {
        let uid = this.ctx.params.id;
        let user = await userList.find(user => user.id == uid);
        console.log(user)
        this.ctx.body = {
            msg: 'ok',
            data: user
        }
    }

    // 添加用戶
    async create() {
        let user = this.ctx.request.body
        await userList.push(user);
        this.ctx.body = {
            msg: 'ok',
            data: userList
        }
    }
}

module.exports = UserController;

4.配置路由(在router.js文件中添加請求映射)

  // 查詢用戶列表
  router.get('/user/list', controller.user.list);
  // 根據id查詢用戶
  router.get('/user/info/:id', controller.user.detail);
  // 添加用戶
  router.post('/user/create', controller.user.create);

如圖所示:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM