eggjs validate no function 解决方案

按着官网的教程https://eggjs.org/zh-cn/basics/controller.html

博主原创,转载记得放本博文链接。原创不易

先上效果

结果卡在一步;

结果发现代码跑不了,看了下,

实际卡在两个位置

1、eggjs报错   validate no function 

2、怎么用post请求 这个接口

先贴出官网的代码,其实是要多配置些东西

const Controller = require('egg').Controller;
class PostController extends Controller {
  async create() {
    const { ctx, service } = this;
    const createRule = {
      title: { type: 'string' },
      content: { type: 'string' },
    };
    // 校验参数
    ctx.validate(createRule);
    // 组装参数
    const author = ctx.session.userId;
    const req = Object.assign(ctx.request.body, { author });
    // 调用 Service 进行业务处理
    const res = await service.post.create(req);
    // 设置响应内容和响应状态码
    ctx.body = { id: res.id };
    ctx.status = 201;
  }
}
module.exports = PostController;

我们先解决第一个问题吧

按着我的流程来

1、先下载egg-validate

项目的package.json 打开 在dependencies 下加一行"egg-validate": "^2.0.2",然后 cnpm install  

2、config/config.default.js  加一行

config.validate = {
	  convert: true,	//对参数可以使用convertType规则进行类型转换
	  // validateRoot: false,
	};

3、config/plugin.js 加一行

exports.validate = {
  enable: true,
  package: 'egg-validate',
};

4、其实到这里  验证就可以了,但是还不能post访问,下面来建个 post的页面

app/controller/test1.js

const Controller = require('egg').Controller;
class test1 extends Controller{
	async index(){
		const {ctx}=this;
		await ctx.render('test1/test1.tpl');
	}
	async postForm(){
		const {ctx}=this;
		
		const createRule={
			title:{type:'string'},
			content:{
				type:'number'
			}
		}
		try{
			//ctx.validate(createRule) 默认  去验证ctx.request.body  如要样验证链接 参数  可以   ctx.validate(createRule,ctx.query)
			ctx.validate(createRule)
		}catch(err){
			ctx.body="类型错误"
			return;
		}
		
		ctx.body="类型正确"
		// const author =ctx.session.userId;
		//  const req = Object.assign(ctx.request.body, { author });
		// const req=await service.post.create(req);
		// ctx.body={id:res.id};

		// ctx.status =201;    
	}
}

module.exports = test1;

5、app/view/test1/test1.tpl 


<html>
  <head>
    <title>Hacker News</title>
    
  </head>
  <body>
   		<form action="/test1/postForm" method="post">
		  <input type="text" name="title" placeholder="title">
		  <input type="text" name="content" placeholder="content">
		  <input type="submit" value="提交">
		</form>
  </body>
</html>

6、 app/router.js 里面加两行

router.get('/test1',controller.test1.index);
router.post('/test1/postForm',controller.test1.postForm);

7、好这样你就可以打开http://localhost:7001/test1访问了,

8、如果你找了半天,用我的方法搞定了,希望你能打赏下

博主原创,转载记得放本博文链接。原创不易

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雪狼之夜

打个赏,让博主知道博文没白写

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值