I'm new in NodeJS, and I'm struggling a little bit on this. I'm using Express and to validate the data, I'm using 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.
So let's take a look at the code.
The route.js file:
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:
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:
module.exports = {
validateCreate: celebrate({...})
}
I think you did something wrong with module exports
try something like this:
module.exports = {
validateCreate: function() {},
otherMethod: function() {},
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.