【问题标题】:TypeScript Joi: Property 'validate' does not exist on type 'Root'TypeScript Joi:“根”类型上不存在属性“验证”
【发布时间】:2020-04-26 16:25:16
【问题描述】:

我不明白为什么我收到错误 Property 'validate' does not exist on type 'Root'.ts(2339)Parameter 'err' implicitly has an 'any' type.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 };

【问题讨论】:

  • 嗨,Bill,你找到解决这个问题的方法了吗??

标签: node.js express joi


【解决方案1】:

要验证,您可以使用以下代码:

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

希望能成功

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2018-08-17
    • 1970-01-01
    • 2023-02-06
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-11-09
    • 2021-07-11
    相关资源
    最近更新 更多