33

there are several issues with the same theme, but I could not solve my problem.

Error: Route.post() requires callback functions but got a [object Undefined]
at Route.(anonymous function) [as post] (/home/kevin/proyectoApp/node_modules/express/lib/router/route.js:196:15)
at EventEmitter.app.(anonymous function) [as post] (/home/kevin/proyectoApp/node_modules/express/lib/application.js:481:19)
at module.exports (/home/kevin/proyectoApp/app/rutas.js:7:5)
at Object.<anonymous> (/home/kevin/proyectoApp/index.js:21:26)
at Module._compile (module.js:398:26)
at Object.Module._extensions..js (module.js:405:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:430:10)
at startup (node.js:141:18)
at node.js:1003:3

Index.js

var express=require('express');
var app=express();
var morgan=require('morgan')
var mongoose=require('mongoose');
var bodyParser=require('body-parser');
var methodOverride=require('method-override');

mongoose.connect('mongodb://localhost/local');


app.use(express.static(__dirname+'/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())


//Endpoints
require('./app/rutas.js')(app);


var server=app.listen(3001,function () {
var host = "localhost";
var port = server.address().port;

console.log('servidor escuchando en http://%s:%s', host, port);});
module.exports=app;

rutas.js

var Controller=require('./controller.js');
var User=require('./models/user.js');

module.exports=function(app){

app.get('/user/all',Controller.Read);

app.put('/user/all/:todo_id',Controller.Update);

app.post('/user/all',Controller.Create);

app.delete('/user/all/todo_id',Controller.Delete);


app.get('/',function(req,res){
console.log("Este si carga");
res.sendFile('./public/index.html');
});
 }

user.js

var mongoose=require('mongoose');
var Schema=mongoose.Schema;

var Schemausuario=new Schema({
nombre:String,
apellido:String,
username:{type:String,requiere:true,unique:true}
});

var User=mongoose.model('User',Schemausuario);

module.exports=User;

controller.js

var User=require('./models/user.js');

var Create=function (req,res){
var nombre=req.body.nombre;
var apellido=req.body.apellido;
var nick=req.body.username;
console.log("Datos"+nombre+apellido+nick);
User.create({
nombre:nombre,
apellido:apellido,
username:nick

},function(err,usr){

if( err) console.log("Error al crear el usuario");
else{
    console.log("Usuario creado correctamente");
}
});

User.find({},function(err,user){
if(err) console.log("Hay un error al buscar los usuarios");
else{
    console.log("Los usuarios encontrados son "+user)
       res.json(user);
            }        
});

};


var Read=function (req,res){

User.find({},function(err,user){
if(err) return console.log("error="+err);
else{
       res.json(user);
            }        
});
};



var Update=function(req,res){
User.update( {_id : req.params.todo_id},
                {$set:{nombre : req.body.nombre,apellido:    req.body.apellido, username: req.body.username}}, 
                function(err, persona) {
                    if (err)
                        res.send(err);

            // Obtine y devuelve todas las personas tras crear una de     ellas
            User.find(function(err, user) {
                if (err)
                    res.send("Ha habido un error"+err)
                console.log("Se va a enviar "+persona)
                res.json(user);
            });
        });
};


var Delete=function(req,res){

  User.remove({
    _id: req.params.todo_id
}, function(err, todo) {
    if(err){
        res.send("Hay un error hdp"+err);
    }
    else{
        console.log("Usuario eliminado correctamente")
    }
    });

    User.find({},function(err, todos) {
        if(err){
            res.send(err);
        }
        res.json(todos);
    });
};

module.exports={
Create:Create,
Update:Update,
Read:Read,
Delete:Delete
}

I use the version "express", "^ 4.13.3"

can you help me? thanks. any other details that I'll upload it finds omitted. any other details that I'll upload it finds omitted.

Kevin AB
  • 543
  • 1
  • 4
  • 8
  • 1
    I solved this problem by following the details included in [this Stack Overflow response](https://stackoverflow.com/a/69828684/14193416) – C RICH Nov 03 '21 at 16:52

28 Answers28

57

Instead of this:

app.post('/user/all',Controller.Create);

You try for:

app.post('/user/all', function(req, res){
  Controller.Create
});
Subburaj
  • 5,114
  • 10
  • 44
  • 87
38

In my case it was because I had a misspelling between the router and controller file. Check both so that they match, the error .POST() requires callback functions but got a [object Undefined] has nothing to do with the real problem.

Ignacio Ara
  • 2,476
  • 2
  • 26
  • 37
14

You are only missing

module.exports = app, or whatever you are exporting. This happened to me many times.

Godstime
  • 365
  • 7
  • 14
5

You want to be sure to check that your spellings are correct for the export and the import. Also make sure your middleware are properly exported and imported.

From the code you are sharing, you should export each middleware individually as exports.Create, exports.Update etc. Setting up your export this way will make it possible to access it the way you are currently accessing it view the Controller variable in your rutas.js file.

Rex Osariemen
  • 151
  • 2
  • 4
4

I got this error when I declared the function in routes but forgot to define it in the controller.

Snow
  • 411
  • 5
  • 8
3

Another case, which I ran into. I was importing from the controller a method called

const { createTrade } = require(...)

But I also had

exports.createTrade = async (..) => { ...

In another part of this file I referenced the createTrade from the import but it was confused about using the exports.createTrade or the imported one. I had to switch to

const controller = require(...)

controller.createTrade
Jason G
  • 2,395
  • 2
  • 24
  • 34
3

In my case, I was Destructuring the export while importing.

if you did module.exports = something, you need to do const something = require('./dir') But if you did module.exports = { something }, you need to do const { something } = require('./dir')

Ali Bin Naseer
  • 113
  • 2
  • 8
2

Always ensure the export name is the same as the import name

//Function Exported
exports.isAuthenticatedUser = catchAsyncErrors(async(req, res, next) => {
}


//Function Imported
const {isAuthenticatedUser} = require('../middlewares/auth');
2

For me it was a simple, stupid typo.

I had module.export = { instead of module.exports = {

user1118374
  • 164
  • 3
  • 12
2

I was having the same issue the way i resolved it was i did comment every post command and then i tested all the post commands one by one and in the 2nd last command when i checked routuer there was a typo error and that was that function wasnt called.

1

In my case this was due to a circular dependency in the file - file A imported functions from file B, but file B imported functions from file A.

LachoTomov
  • 3,312
  • 30
  • 42
1

In my case, I've encountered this error when I have deleted a function in my controller.js file but forgot to remove it in the router definition.

for eg,

router.get('/', controller.getUsers);

So, in the above code, I've deleted that getUsers() function in the controller.js file but I still used it in the route definition. So after removing this useless route the problem gets solved. Hope this error helps someone.

somesh
  • 63
  • 7
1

In my case I didnot exported the function of controller

  • This answer is more suitable as a comment, try enhancing your answer by providing an example on how to solve OP's problem. (e.g. how to export a function and which function exactly.) – posixpascal Jun 03 '22 at 13:14
0

This error usually comes when you mistakenly import functions in the wrong way, or may be a spelling mistake Both the controller and the route are in some trouble.

I encountered this when I was exporting a function from the controller which was all good.

exports.addCategory = (req,res) => {}

but when I was importing it in the routes I was doing

const addCategory = require('../Controllers/Category')

instead

const {addCategory) = require('../Controllers/Category')

you see that curly braces around addCategory while importing So, I was importing the entire function, which was wrong

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
Sourabh
  • 207
  • 2
  • 2
0

I resolve this problem adding

module.exports = new ExampleController();

just adding new.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
0

do not export your controller like this

module.exports.createPost = () => {..}

instead of export like this

module.exports = {
    createPost,
}

and import the controller like this,

postRouter.post("/createNew_post", postControllers.createPost);
0

I had the same error, this was my mistake:

Controller:

module.exports = cargarArchivo;

Route:

const { cargarArchivo } = require('../controllers/uploads');
const { Router } = require('express');
const router = Router();

router.post( '/', cargarArchivo )

Error:

Error: Route.post() requires a callback function but got a [object Object]

SOLUTION: In the controller change:

module.exports = cargarArchivo;

For:

module.exports = {
  cargarArchivo
}

The problems is I'm exporting the constant as a constant instead exporting it as a property in the controller, then importing it as a property. It has to match both ways.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Germán Acosta
  • 57
  • 1
  • 13
0

Rename the Controller Method Name Work For me. Try it also

0

I stuck for an hour then I resolved these issues, whenever you got these errors then you should understand that you have created a different name convention in admin and AdminMediator. I solved these issues, when I clicked on the required APIs in admin, it doesn't direct me to the desired API in AdminMediator, then I understood why this error occurs.

Thanks

Naffy Kausar
  • 91
  • 2
  • 2
  • 9
0

In my case in the controllers the function login was not defined, but trying to access

For Example:

router.post('/user/login', userController.login)
Jakub Kurdziel
  • 3,216
  • 2
  • 12
  • 22
0

In route.js, instead of importing:

**var Controller=require('./controller.js');

Try this:

var { Controller } = require('./contoller.js');
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
0

It's also quite possible you have a route that is defined but not being used, try looking for that route and deleting both the route and controller

  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Y. Gherbi Jun 16 '22 at 11:07
0

Error: Route.post() requires a callback function but got a [object Undefined]

Remove/comment all other routes which you haven't yet defined (Let's say in your controller).

In my case it worked.

Sigma
  • 1
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32671503) – kavigun Sep 15 '22 at 05:49
0

the error I was getting is :

Route.post() requires a callback function but got a [object Object]

and this was my file: my code at that time userController file from where I was importing enter image description here

the mistake I was doing at that time is importing 2 entities from a file separately instead of de-structuring

this will fix my error enter image description here

  • 1
    Thanks for sharing your experience! It would even be more helpful to provide the code in text form, not in form of images / screenshots. – Ingo Steinke Nov 15 '22 at 15:53
0

This is my code I got the same issues and I found 3 valid solutions if your using module.exports.

when I tried to print the imports from my controller I found it is return empty object {} . so the solutions are

Solution 1: Cross check the name of the files where you exporting and where you importing it in your path.

Solution 2: use require.resolve("...your import path").

example for solution 1 :

before:

const express = require("express");
const router = express.Router();
const createToDo = require("../controllers/CreateToDoController")
router.get("/",(req,res)=>{
    res.send("<h1>Welcome to Homepage</h1>");
})
console.log('todo iss', createToDo);
router.post("/createtodo",(req,res)=>createToDo(res,req));
module.exports = router;

after:

const express = require("express");
const router = express.Router();
const createToDo = require.resolve("../controllers/CreateToDoController")
router.get("/",(req,res)=>{
    res.send("<h1>Welcome to Homepage</h1>");
})
console.log('todo iss', createToDo);
router.post("/createtodo",(req,res)=>createToDo(res,req));
module.exports = router;

Solution 3:

Wrap the controller function inside callback. Better to use arrow function to make it one line:

here is the code before change: Todocontroller.js

//importing model
const toDoModel = require('../models/ToDoModel');

//creating controller function
const createToDoController = async (req,res)=>{
    try{
    const {title,toDoTasks} = req.body;

    if(!title) //input validation
    { 
        throw new Error("Please provide the title");
    }
    const newToDo = await toDoModel.create({ title, tasks:toDoTasks?toDoTasks:[] });
    res.status(201).json({
        success: true,
        message: "User Created Successfully",
        newToDo,
      });
    }
    catch(err){
        res.status(500).json({
            success: false,
            message: "Unable to perform create operation",
            error: err
        })
        res.send(err.message);
    } 

}
module.exports = createToDoController;

router.js

const express = require("express");
const router = express.Router();
const createToDo = require("../controllers/CreateToDoController")
router.get("/",(req,res)=>{
    res.send("<h1>Welcome to Homepage</h1>");
})
console.log(`todo iss ${createToDo}`);
router.post("/createtodo",createToDo);
module.exports = router;

I have change the line from router.post("/createtodo",createToDo); to router.post("/createtodo",(req,res)=>createToDo(res,req));

I don't understand why this is happening but yeah this is only solution working for me. if you got better solutions please mention in discussions :)

Indratej Reddy
  • 165
  • 1
  • 7
0

In my case, adding {} around the importing variable was sufficient to solve the error:

const {registerUser}=require("../controllers/userController");
J. Murray
  • 1,460
  • 11
  • 19
0

You might have misspelled controller.create in controller or routes file

-1

yes Subburaj is correct, Implement in app.js

app.post('/sign', function (req, res) {
    LoginController.authenticate
});

this could be solve the problem