Egg学习笔记

1. 创建项目

安装egg.js

# 全局切换镜像: 
npm config set registry https://registry.npmmirror.com

我们推荐直接使用脚手架,只需几条简单指令,即可快速生成项目(npm >=6.1.0):

mkdir egg-example && cd egg-example
npm init egg --type=simple --registry https://registry.npmmirror.com
npm i
npm run dev

2. 关闭csrf开启跨域

安装跨域插件

npm i egg-cors --save

配置插件

// {app_root}/config/plugin.js
cors:{
  enable: true,
  package: 'egg-cors',
}


// config/config.default.js 
config.security = {
  // 关闭 csrf
  csrf: {
    enable: false,
  },
  // 跨域白名单
  domainWhiteList: ["http://localhost:3000"],
};
// 允许跨域的方法
config.cors = {
  origin: "*",
  allowMethods: "GET, PUT, POST, DELETE, PATCH",
};

3. 全局抛出异常处理

// app/middleware/error_handler.js
module.exports = (option, app) => {
  return async function errorHandler(ctx, next) {
    try {
      await next();
      // 404 处理
      if (ctx.status === 404 && !ctx.body) {
        ctx.body = {
          msg: "fail",
          data: "404 错误",
        };
      }
    } catch (err) {
      // 记录一条错误日志
      app.emit("error", err, ctx);

      const status = err.status || 500;
      // 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
      const error = status === 500 && app.config.env === "prod"
        ? "Internal Server Error"
        : err.message;

      // 从 error 对象上读出各个属性,设置到响应中
      ctx.body = {
        msg: "fail",
        data: error,
      };
      ctx.status = status;
    }
  };
};

// config/config.default.js
config.middleware = ["errorHandler"];

4. 封装api返回格式扩展

// app/extend/context.js
module.exports = {
  // 成功提示
  apiSuccess(data = "", msg = "ok", code = 200) {
    this.body = { msg, data };
    this.status = code;
  },
  // 失败提示
  apiFail(data = "", msg = "fail", code = 400) {
    this.body = { msg, data };
    this.status = code;
  },
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值