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;
},
};