入门笔记请按照官方文档初始化一个简单的项目,按照下面的步骤学习,不明白的请参考官方文档。按以下步骤禁止csrf验证控制创建,执行Post操作时会出现invalidcsrftoken错误。需要禁用此功能。创建路由/***@param{Egg.Application}app-egg应用*/module.exports=app=>{const{router,controller,}=app;router.get('/',controller.home.index);//创建一个新的资源路由router.resources('SystemUser','/system/user',controller.system.user);};controllercontroller.system.user对应controller目录下的system目录user.js文件创建对应controllerconstController=require('egg').Controller;classSystemUserControllerextendsController{asyncindex(){const{ctx,}=这个;ctx.body='你好!这是系统用户控制器';}}module.exports=SystemUserController;访问地址:localhost:7001/system/user创建一个可以提交数据的controller方法constController=require('egg').Controller;classSystemUserControllerextendsController{asyncindex(){const{ctx,}=this;ctx.body='你好!这是系统用户控制器';}asynccreate(){constctx=this.ctx;constuser=ctx.request.body;ctx.body=用户;}}module.exports=SystemUserController;POST方法访问URL:localhost:7001/system/user会提示invalidcsrftoken错误关闭csrf验证//config\config.default.js//关闭csrf验证config.security={csrf:{enable:false,},};启用验证在上面的例子中,我们通过表单提交的任何数据都会被回显到界面上。如果需要存储数据或进行其他业务处理,则需要对用户输入的数据进行校验。egg提供了用于表单验证的egg-validate插件。安装插件cnpminstallegg-validate--saveconfiguration启用插件/**@typeEgg.EggPlugin*/module.exports={//hadenabledbyegg//static:{//enable:真,//}验证:{启用:真,包:'egg-validate',},};首先使用验证组件创建一个规则,这里我们定义用户名是一个字符串,并且是必需的,最大长度为8个字符。将密码定义为字符串,并且必须至少包含6个字符。ctx.validate(createRule,ctx.request.body);通过以上语句查看参数。更多规则请参考:https://github.com/node-modul...constController=require('egg').Controller;//定义本接口请求参数的校验规则constcreateRule={用户名:{类型:'string',要求:true,最大值:8,},密码:{类型:'string',要求:true,最小值:6,},};classSystemUserControllerextendsController{asyncindex(){const{ctx,}=这个;ctx.body='你好!这是系统用户控制器';}asynccreate(){constctx=this.ctx;//验证输入参数是否符合预期格式ctx.validate(createRule,ctx.request.body);constuser=ctx.request.body;ctx.body=用户;}}module.exports=SystemUserController;测试使用POSTMAN提交任意字段,会提示ValidationFailed(code:invalid_param)如何查看具体错误信息。下面会定义统一错误处理的中间件来进行错误处理。统一错误处理中间件在项目的app目录下创建一个middleware目录,可以在该目录下创建middleware。创建错误处理中间件'usestrict';module.exports=()=>{returnasyncfunctionerrorHandler(ctx,next){try{awaitnext();}catch(err){//控制台输出console.error('MiddleWareerrorHandler',err);//所有的异常都会在app上触发一个error事件,框架会记录一个errorlogctx.app.emit('error',err,ctx);//status如果没有,则统一为500conststatus=err.status||500;//如果是500错误,而且是生产环境,统一显示“InternalServerError”consterror=status===500&&ctx.app.config.env==='prod'?“内部服务器错误”:错误;//改变上下文状态码ctx.status=status;//从错误对象中读取每个属性并将其设置为响应ctx.body={error,};}};};启用中间件文件configconfig.default.js//在此处添加中间件配置config.middleware=[];修改它以包含您创建的中间件//在此处添加您的中间件配置//errorHandler统一错误处理config.middleware=['errorHandler'];//errorHandler只对/api生效config.errorHandler={match:'/api',};如上所示,您可以根据输入的URL设置错误处理中间件。这里我们使用/api测试路由先访问原来的路由:localhost:7001/system/user报错还是改了路由:打开文件:approuter.js//router.resources('SystemUser','/system/用户',controller.system.user);router.resources('SystemUser','/api/v1/system/user',controller.system.user);再次访问:localhost:7001/api/v1/system/user提示信息会变成:{"error":{"message":"ValidationFailed","code":"invalid_param","errors":[{"message":"required","field":"username","code":"missing_field"},{"message":"required","field":"password","code":"missing_field"}]}}格式化接口返回的数据结构在上面显示的错误信息中,可以看到标准化的Json数据,如果我们开发一个接口,我们需要定义一个统一的数据结构供客户端解析。API开发中,可以定义接口的标准返回格式。通过框架扩展定义返回数据格式是一种非常方便的方法。在app目录下创建一个extend目录,扩展egg的内置对象Helper。创建Helper扩展文件:app/extend/helper.js'usestrict';module.exports={/***正常情况下调用返回数据包*@param{Object}ctx-context*@param{*}msg-message*@param{*}data-数据*/success(ctx,msg,data){ctx.body={code:0,msg,data,};ctx.status=200;},/***处理失败,处理传入失败原因*@param{*}ctx-上下文*@param{Object}res-返回状态数据*/fail(ctx,res){ctx.body={code:res.code,msg:res.msg,data:res.data,};ctx.status=200;},};改进统一的错误处理//从错误对象中读取每个属性并设置到响应中//ctx.body={//error,//};//格式化返回错误信息ctx.helper.fail(ctx,{code:status,msg:error.message,data:error.errors,});再次测试访问:localhost:7001/api/v1/system/user提示信息会变成:{"code":422,"msg":"ValidationFailed","data":[{"message":"required",“字段”:“用户名”,“代码”:“missing_field”},{“消息”:“必填”,“字段":"password","code":"missing_field"}]}将controlleruser中的返回改为标准格式asynccreate(){constctx=this.ctx;//验证输入参数是否符合预期formatctx.validate(createRule,ctx.request.body);constuser=ctx.request.body;//ctx.body=user;this.ctx.helper.success(this.ctx,'ok',user);}提交满足要求的数据,测试正确返回数据用户名testuser密码1234567890提交后返回标准数据格式{"code":0,"msg":"ok","data":{"username":"testuser","密码”:“1234567890”}}
