【问题标题】:AJV - "standaloneCode is not a function"AJV - “standaloneCode 不是函数”
【发布时间】:2021-05-14 18:01:18
【问题描述】:

我正在尝试为我的 Express 后端编写一个“注册”验证器。我为此使用 AJV。显然,我想将验证器模式导出为模块,因此我正在关注 AJV 文档中的 this 页面。但是我不断收到:TypeError: standaloneCode is not a function

这是我的代码:

const Ajv = require("ajv")
const ajv = new Ajv({ code: { source: true } })
const standaloneCode = require("ajv/dist/standalone")

const signupSchema = {
  type: "object",
  properties: {
    username: { type: "string" },
    email: { type: "string" },
    password: { type: "string" },
    confirmPassword: { type: "string" },
  },
  required: ["username", "email", "password", "confirmPassword"],
}

const validate = ajv.compile(signupSchema)

const moduleCode = standaloneCode(ajv, validate)

module.exports =  moduleCode

提前谢谢你。

【问题讨论】:

  • 一般提示:尝试调试或控制台记录 standaloneCode 是什么。也许图书馆作者更改了它并将其包装在一个对象中?
  • 这是一个“默认”ESM导出,调用require时需要使用const standaloneCode = require('ajv/dist/standalone').default
  • 谢谢,添加 .default 有效

标签: javascript node.js express validation ajv


【解决方案1】:

这似乎是 AJV 文档 (https://ajv.js.org/standalone.html) 中的一个错误。捆绑的 standalone 模块具有 ESM 样式导出,因此在使用 require 时需要明确引用 .default

const standaloneCode = require('ajv/dist/standalone').default

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2018-10-23
    • 2017-05-06
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多