Egg.js项目搭建

这是我参与更文挑战的第4天,活动详情查看: 更文挑战

一、利用脚手架快速搭建项目

$ mkdir egg-example && cd egg-example
$ npm init egg --type=simple
$ npm i
复制代码

项目目录

image.png

egg-project
├── package.json
├── app.js (可选)
├── agent.js (可选)
├── app (重点关注)
|   ├── router.js
│   ├── controller
│   |   └── home.js
│   ├── service (可选)
│   |   └── user.js
│   ├── middleware (可选)
│   |   └── response_time.js
│   ├── schedule (可选)
│   |   └── my_task.js
│   ├── public (可选)
│   |   └── reset.css
│   ├── view (可选)
│   |   └── home.tpl
│   └── extend (可选)
│       ├── helper.js (可选)
│       ├── request.js (可选)
│       ├── response.js (可选)
│       ├── context.js (可选)
│       ├── application.js (可选)
│       └── agent.js (可选)
├── config (重点关注)
|   ├── plugin.js
|   ├── config.default.js
│   ├── config.prod.js
|   ├── config.test.js (可选)
|   ├── config.local.js (可选)
|   └── config.unittest.js (可选)
└── test
    ├── middleware
    |   └── response_time.test.js
    └── controller
        └── home.test.js
复制代码

搭建成功

image.png

二、开始尝试创建第一个mock接口

1. 在home.js中新建一个list方法

 async list() {
    this.ctx.body = {
      msg: 'ok',
      list: [1,2,3,4,5]
    }
  }
复制代码

2. 在route.js中注册路由

router.get('/list', controller.home.list);
复制代码

3.运行成功

image.png

三、尝试新创一个路由

1. 环境准备,vscode安装egg.js插件,便于代码提示。

image.png

2. 新建一个路由

egg controller
复制代码

image.png

3. 在新的user.js路由中新建一个api

'use strict';

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

class UserController extends Controller {
  async list() {
    let res = {
        msg: 'ok',
        data: [
            {
                id: '1',
                username: '张三',
                nickname: 'zs',
                sex: '男'
            },
            {
                id: '2',
                username: '王五',
                nickname: 'ww',
                sex: '女'
            },
        ]
    }
    const {ctx} = this
    ctx.body = res
  }
}

module.exports = UserController;

复制代码

4. 在router.js中配置路由

image.png
新建路由成功

image.png

五、路由的两种传参方式

一、Params(restful风格)

'use strict';

const Controller = require('egg').Controller;
const userList = [
  {
    id: '1',
    username: '张三',
    nickname: 'zs',
    sex: '男'
  },
  {
    id: '2',
    username: '王五',
    nickname: 'ww',
    sex: '女'
  },
]

class UserController extends Controller {
  async list() {
    const { ctx } = this
    let res = {
      msg: 'ok',
      data: userList
    }
    ctx.body = res
  }

  async info1() {
    const { ctx } = this
    let userDetail = userList.find(v => v.id === ctx.params.id)
    let res = {
      msg: 'ok',
      data: userDetail
    } 
    ctx.body = res
  }

}

module.exports = UserController;

复制代码

image.png

运行效果

image.png

二、query方式

async info2() {
    const { ctx } = this
    let userDetail = userList.find(v => v.id === ctx.query.id)
    let res = {
      msg: 'ok',
      data: userDetail
    } 
    ctx.body = res
  }
复制代码
router.get('/user/info2', controller.user.info2)
复制代码

image.png

六、关闭CSRF安全

新建一个post请求,使用postman测试会访问被拒绝

router.post('/user/create', controller.user.create)
复制代码

image.png

解决方案

1.安装跨域插件

npm i egg-cors --save
复制代码

2. 配置config/plugin.js

cors: {
    enable: true,
    package: 'egg-cors'
  }
复制代码

3. 配置config/config.default.js

  // 关闭csrf开启跨域
  config.security = {
    // 关闭 csrf
    csrf: {
      enable: false
    },
    // 跨域白名单  'http://localhost:3000'
    domainWhiteList: []
  }
  // 允许跨域的方法
  config.cors = {
    origin: '*',
    allowMethods: 'GET,PUT,POST,DELETE,PATCH'
  }
复制代码

image.png

4. post请求接参数

async create() {
    const { ctx } = this
    let params = ctx.request.body
    let res = {
      msg: 'ok',
      data: {
        id: '3',
        username: params.username,
        nickname: params.nickname,
        sex: params.sex
      }
    } 
    ctx.body = res
  }
复制代码

测试效果

image.png

七、资源路由

按之前那种路由写法,每个方法都需要写一个路由与之匹配,有没有可以分组的方式。

'use strict';

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

class PostController extends Controller {
  // 列表页
  async index() {
    this.ctx.body ='列表页'
  }
  // 新增表单页
  async new() {
    this.ctx.body ='新增表单页'
  }
  // 新增逻辑
  async create() {
    this.ctx.body ='新增逻辑'
  }
  // 详情页
  async show() {
    this.ctx.body ='详情页'
  }
  // 编辑表单页
  async edit() {
    this.ctx.body ='编辑表单页'
  }
  // 更新逻辑
  async update() {
    this.ctx.body ='更新逻辑'
  }
  // 删除逻辑
  async destroy() {
    this.ctx.body ='删除逻辑'
  }
}

module.exports = PostController;
复制代码

然后在router.js中标识一下

 // 资源路由
  router.resources('post','/api/post',controller.post)
复制代码

请求效果

image.png

八、路由分模块

1. 在新建route文件夹,分模块写js

例如post.js中

module.exports = app => {
    const { router, controller } = app;
    // user.js
    router.get('/user/list', controller.user.list)
    router.get('/user/info1/:id', controller.user.info1)
    router.get('/user/info2', controller.user.info2)
    router.post('/user/create', controller.user.create)
  };
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享