Node + Express. Routing error .post route. Expected callback received object

I am currently working on an application using Express + Node. I recently added a new .post route to the app.js file using the following syntax:

 app.post('/api/posts/saveComment', posts.saveComment); 

posts defined above as:

 var posts = require('./routes/posts.js'); 

And saveComment is defined like this:

 exports.saveComment = function(req, res) { //function stuff in here, yada yada } 

Now node throws an error when trying to start the application:

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

saveComment is obviously a function, I do not understand why it does not see this. I have another function, defined directly above saveComment , that I can completely reference without errors, however copying the contents of functions with saveComment still leads to the same error. I am at a loss, any help is greatly appreciated.

Upon request, posts.js content

 var mongo = require('../mongo.js'); exports.queryAll = function(req, res) { var db = mongo.db; db.collection('posts', function(err, collection) { collection.find().toArray(function(err, doc) { if (err) res.send({error:err}) else res.send(doc) res.end(); }); }); } exports.saveCommment = function(req, res) { var db = mongo.db, BSON = mongo.BSON, name = req.body.name, comment = req.body.comment, id = req.body.id; db.collection('posts', function(err, collection) { collection.update({_id:new BSON.ObjectID(id)}, { $push: { comments: { poster:name, comment:comment }}}, function(err, result) { if (err) { console.log("ERROR: " + err); res.send(err); } res.send({success:"success"}); res.end(); }); }); } 
+4
source share
3 answers

Well ... an embarrassing answer, saveCommment is defined with 3 m in my posts.js . Ugh.

+10
source

Have you considered other related issues?

For instance:

Understanding callbacks in Javascript and node.js

understanding the concept of javascript callbacks with node.js, especially in loops

I struggled with this topic myself and I must say that callbacks are fundamental to a happy node.js application.

Hope this helps.

0
source

I write my export as follows. maybe this will help you :)

  module.export = { savecomment : function(){ yada yada }, nextfunction : function(){ } } 

Using functions:

  var helper = require('helper.js') helper.savecomment(); 
0
source

Source: https://habr.com/ru/post/1499866/


All Articles