node.js - TypeScript Joi : Property 'validate' does not exist on type 'Root'

标签 node.js express joi

我不明白为什么我收到错误类型“Root”.ts(2339)上不存在属性“validate”并且参数“err”隐式具有“any”类型.ts(7006) 我导入了 "@hapi/joi": "^17.0.0"和 "@types/hapi__joi": "^16.0.6"

import Joi from '@hapi/joi';
import { NextFunction, Request, Response } from 'express';
import { WriteError } from 'mongodb';
import sha1 from 'sha1';
import { user } from '../models/user';

class Home {
  static index = async (req: Request, res: Response, next: NextFunction) => {
    try {
        const schema = Joi.object().keys({
          email: Joi.string()
            .lowercase()
            .trim()
            .max(320)
            .email({ minDomainSegments: 2 })
            .required(),
          fullName: Joi.string()
            .trim()
            .max(70)
            .required(),
          password: Joi.string()
            .trim()
            .min(8)
            .max(70)
            .required(),
        });
        const { email, password, fullName } = req.body;
        Joi.validate({ email, password, fullName }, schema, (err, val) => {
//             ^ Error                                 Error ^     ^ Error   
          if (err) {
            throw new Error('Failed to validate input ' + err.details[0].message);
          }
          req.body = val;
          next();
        });
      } catch (error) {
        res.status(400).send({
          code: sha1('validateJoin' + error.message || 'Internal Server Error'),
          error: error.message || 'Internal Server Error',
        });
      }
  };
}

export { Home };

最佳答案

要进行验证,您可以使用下面的代码:

schema.validateAsync({ email, password, fullName }).then(val => {
      req.body = val;
    }).catch(err => {
      throw new Error('Failed to validate input ' + err.details[0].message);
    })

希望能成功

关于node.js - TypeScript Joi : Property 'validate' does not exist on type 'Root' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59657629/

相关文章:

javascript - 尽管使用缓冲区调用,文件类型 npm 模块仍返回 null,我做错了什么?

json - Node JS Joi 验证 - 如何返回 JSON 响应而不是字符串?

node.js - 如何扫描代码是否有弃用或更糟的情况

git - 如何支持一个 git repo 中的多个私有(private) npm 包?

http - Express/NodeJS 无法在发送后发送 header 由 http 请求引起

javascript - "Type RootQueryType must define one or more fields."}

node.js - hapijs joi 电子邮件验证选项 tldWhitelist 用法

javascript - Joi - 默认设置所需的一切?

node.js - 如何将 websocket 二进制消息作为流发送到 Google Speech API?

javascript - MariaDB 与 Sequelize 的连接