按着官网的教程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、如果你找了半天,用我的方法搞定了,希望你能打赏下
博主原创,转载记得放本博文链接。原创不易