nodejs Joi报错:Joi.validate is not a function及解决方式

Joi时是avascript对象的规则语言和验证器,通常可以在用户登录时验证用户信息。

在数据校验时,报错:Joi.validate is not a function

先看代码:

 1 const Joi = require('joi')
 4 const schema = {
 5     username: Joi.string().min(2).max(5).required().error(new Error('username error'))
 6 }
 7 
 8 async function validation() {
 9     try {
10         await Joi.validate({ username: 'ab' }, schema);
11     } catch (ex) {
12         console.log(ex.message);
13         return;
14     }
15     console.log('success');
16 
17 }
18 validation()

报错原因是:joi v16不再支持joi.validate()

解决方案有两种:

方案1: 卸载当前的joi,重新安装支持此语法的joi

//卸载
node uninstall joi

//重新安装版本14.3.1
node install joi@14.3.1

方案2:对于新版本的joi,代码如下

1  const schema = Joi.object({
2         username: Joi.string().min(2).max(5).required().error(new Error('username error'))
3     });
4     const validation = schema.validate(req.body);
5     res.send(validation);

 

posted @ 2021-01-22 06:19  菠菜猫  阅读(724)  评论(0编辑  收藏  举报