Egg的简单使用

Egg的简单使用 - 程序员与产品经理的相爱相杀

Egg是阿里出品的node后端框架,其对koa做了一些封装,使用上更加简单医用。
环境:windows

创建Egg项目

前提是已经安装了node,node的安装这里不重复,默认已经安装了node。

mkdir egg-example
cd egg-example
npm init egg --type=simple
npm install

完成以上步骤便能够创建一个带demo的egg项目


启动项目

npm run dev

从控制台可以看到入口IP和端口

启动项目

npm run dev

在浏览器输入:127.0.0.1:7001
可以看到结果

Egg自带组件的使用

约定俗成的名称:

  1. app/router.js:路由配置
  2. app/controller/xx:controller编写位置
  3. app/service/xx:service编写位置,业务逻辑,与DB交互
  4. app/middleware/xx:中间件编写位置,共用逻辑,如鉴权
  5. app/public/xx:静态资源存放位置
  6. config/config.{env}.js:不同环境的配置文件,默认是config.default.js
  7. config/plugin.js:配置需要加载的插件,包括官方的和自己编写的

    app/router.js

    作用:配置路由。如启动项目后IP+端口,便是路由到home.js中
    更多配置:路由(Router) - Egg

编写基础的接口:Controller

GET方法获取参数

对应请求:

http://127.0.0.1:7001/?userId=zhangsan

获取查询参数param:ctx.query

'use strict';
const { Controller } = require('egg');
class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    const { userId } = ctx.query;
    ctx.body = 'hi, ' + userId;
  }
}
module.exports = HomeController;

获取路径参数parth:ctx.params

// 获取用户信息
  async user() {
    const { ctx } = this;
    const { id } = ctx.params;
    ctx.body = 'hi, 用户:' + id;
  }

POST方法获取参数

获取表单或者JSON:ctx.request.body

获取表单或者JSON:ctx.request.body

 // 添加一个新用户
  async user_add() {
    const { ctx } = this;
    const { title } = ctx.request.body;
    ctx.body = {
        title
    };

controller调用service方法

这里仅仅在service的模拟数据库的返回,突出controller如何调用service。
controller调用service方法:

const { name, slogan } = await ctx.service.home.user();

service方法:

'use strict';
const Service = require('egg').Service;
class HomeService extends Service {
    async user() {
        return {
            name: "张三",
            slogan: "你好,世界"
        }
    };
}
module.exports = HomeService;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值