美文网首页
EGG框架获取表单内容及校验参数示例

EGG框架获取表单内容及校验参数示例

作者: wlyhl | 来源:发表于2018-08-23 08:53 被阅读0次

获取表单内容

新建一个表单html在view中

View 中的html需要用到View引擎,安装egg-view-nunjucks插件

npm i egg-view-nunjucks

然后在config/plugin.js中配置插件启用状态

exports.nunjucks= {

    enable: true,

    package: 'egg-view-nunjucks',

};

在各个环境的配置文件中config/config.${env}.js中配置插件

//config/config.default.js

module.exports = appInfo =>{

  const config = exports= {};

  // use for cookie sign key, should change to your own and keep security

  config.keys = appInfo.name + '_1532569715327_5704';

  config.view= {

    defaultViewEngine: 'nunjucks',

  };

  config.nunjucks= {

    // dir: 'path/to/template/dir',  // default to `{app_root}/app/view`

    cache: true, // local env is false

  };

  return config;

};

在controller目录下新建一个form.js,

//app/controller/form.js

// 处理表单提交后的事件,此处返回表单提交的内容

exports.post = async ctx =>{

    ctx.body = `body: ${JSON.stringify(ctx.request.body)}`;

}

// 渲染静态页面,模拟提交表单

exports.render = async ctx =>{

    await ctx.render('form.html');

}

在router.js中添加

// app/router.js

module.exports = app =>{

  const { router, controller } = app;

  // 表单提交的路径

  router.post('/form', controller.form.post);

  // 模拟表单路径

  router.get('/login', controller.form.render);

};

运行,访问login页面

提交之后,跳转到表单处理页面

表单校验

接上文,如果要验证提交的表单数据内容,可以使用egg-validate,

安装: npm I egg-validate

然后在插件配置中启用该插件

exports.validate= {

    enable: true,

    package: 'egg-validate',

};

修改form.js如下

//app/controller/form.js

// 表单提交的验证规则

const loginRule= {

    username:{

      type: 'email',

    },

    password:{

      type: 'password',

    //  compare: 're-password',

    },

  };

// 处理表单提交后的事件,此处返回表单提交的内容

exports.post = async ctx =>{

    // 如果校验报错,会抛出异常

    try{

      ctx.validate(loginRule);

    }catch (error) {

      console.log(error)

    }

    ctx.body = `body: ${JSON.stringify(ctx.request.body)}`;

}

// 渲染静态页面,模拟提交表单

exports.render = async ctx =>{

    await ctx.render('form.html');

}

运行,输入不符合验证的数据

结果

因为异常被捕获了,此时不会跳到422页面,但是在控制台中可以看到捕获的异常

输入正常的数据

校验正常,控制台也没有异常输出

相关文章

网友评论

      本文标题:EGG框架获取表单内容及校验参数示例

      本文链接:https://www.haomeiwen.com/subject/wxfpiftx.html