简体   繁体   English

如何从 NodeJS 中的另一个文件导入函数?

[英]How to import functions from another file in NodeJS?

I'm new in NodeJS, and I'm struggling a little bit on this.我是 NodeJS 的新手,我在这方面有点挣扎。 I'm using Express and to validate the data, I'm using Celebrate .我正在使用Express并验证数据,我正在使用Celebrate

I've got a route.js file, where I make a POST request, using a function from another file to do so (it's the create function, from MyController . It works fine! But when I try to do the same thing to my validator , it doesn't work.我有一个route.js文件,我在其中发出POST请求,使用另一个文件中的 function 来执行此操作(它是来自MyController创建function。它工作正常!但是当我尝试对我的验证器,它不起作用。

So let's take a look at the code.那么让我们看一下代码。

The route.js file: route.js文件:

const express = require("express");

const MyController = require("./controllers/MyController");
const MyValidator= require("./validators/MyValidator");

const routes = express.Router();

routes.post("/path", MuValidator.validateCreate, MyController.create);

The MyValidator file: MyValidator文件:

module.exports = {

  validateCreate() {
    celebrate({
      [Segments.HEADERS]: Joi.object({
        authorization: Joi.string().required(),
      }).unknown(),
      [Segments.BODY]: Joi.object().keys({
        userId: Joi.string().required(),
        title: Joi.string().required(),
        description: Joi.string().required(),
        value: Joi.number().required(),
        dueDate: Joi.string().required(),
      }),
    });
  },
}

IMPORTANT : I only get this working, if I write the validation code directly on my route, like this:重要提示:如果我直接在我的路线上编写验证代码,我只会得到这个工作,如下所示:

routes.post(
  "/path",
  celebrate({
    [Segments.HEADERS]: Joi.object({
      authorization: Joi.string().required(),
    }).unknown(),
    [Segments.BODY]: Joi.object().keys({
      userId: Joi.string().required(),
      title: Joi.string().required(),
      description: Joi.string().required(),
      value: Joi.number().required(),
      dueDate: Joi.string().required(),
    }),
  }),
  MyController.create
);

the problem is that the celebrate function creates and returns a middleware, so the middleware returned by the celebrate function must be passed as second parameter to the post but you're passing a function that execute the celebrate method instead, so validateCreate should be: the problem is that the celebrate function creates and returns a middleware, so the middleware returned by the celebrate function must be passed as second parameter to the post but you're passing a function that execute the celebrate method instead, so validateCreate should be:

module.exports = {
    validateCreate: celebrate({...})
}

I think you did something wrong with module exports我认为您在模块导出方面做错了

try something like this:尝试这样的事情:

module.exports = {
    validateCreate: function() {},
    otherMethod: function() {},
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM