Error: .post() requires callback functions but got a [object Undefined] not working

偶尔善良 提交于 2021-02-06 02:34:28

问题


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.


回答1:


Instead of this:

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

You try for:

app.post('/user/all', function(req, res){
  Controller.Create
});



回答2:


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.




回答3:


You are only missing

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




回答4:


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.




回答5:


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');



回答6:


For me it was a simple, stupid typo.

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




回答7:


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




回答8:


yes Subburaj is correct, Implement in app.js

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

this could be solve the problem



来源:https://stackoverflow.com/questions/34853675/error-post-requires-callback-functions-but-got-a-object-undefined-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!