Node + Express .post路由抛出错误。 预期的callback,得到的对象
我目前正在使用Express + Node开发应用程序。 我最近添加了一个新的.post
path到app.js
文件,使用下面的语法:
app.post('/api/posts/saveComment', posts.saveComment);
posts
在上面被定义为:
var posts = require('./routes/posts.js');
saveComment
定义如下:
exports.saveComment = function(req, res) { //function stuff in here, yada yada }
现在,当我尝试运行应用程序时,节点发生错误:
Error: .post() requires a callback functions but got a [object Undefined]
saveComment
显然是一个函数,我不明白为什么看不到这个。 我有上面saveComment
定义的另一个函数,我能够完全正确地引用没有错误,但是将该函数的内容复制到saveComment
仍然会产生相同的错误。 我很茫然,任何帮助,非常感谢。
根据请求, posts.js
内容
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(); }); }); }
那么…尴尬的答案, saveCommment
定义为在我的posts.js
3米。 啊。
你有没有看过其他相关的问题?
如:
了解Javascript和node.js中的callback
通过node.js理解javascriptcallback的概念,特别是在循环中
我已经自己与这个话题作斗争,不得不说,callback是一个快乐的node.js应用程序的基础。
希望这可以帮助。
我按照以下方式编写我的输出。 也许这会帮助你:)
module.export = { savecomment : function(){ yada yada }, nextfunction : function(){ } }
使用function:
var helper = require('helper.js') helper.savecomment();