zoukankan      html  css  js  c++  java
  • 使用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);

    如图所示:

  • 相关阅读:
    画了朵花
    定位
    浮动
    盒模型
    html+css笔记1
    闭包
    高阶函数
    函数
    Map Set iterable
    git stash clear/drop 后代码如何恢复
  • 原文地址:https://www.cnblogs.com/jun1019/p/14447039.html
Copyright © 2011-2022 走看看