问题描述
我目前正在使用Express + Node开发应用程序.我最近使用以下语法向app.js
文件添加了新的.post
路由:
I'm currently working on an app 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
在上面的定义为:
var posts = require('./routes/posts.js');
saveComment
的定义如下:
exports.saveComment = function(req, res) {
//function stuff in here, yada yada
}
现在,当我尝试运行应用程序时,节点抛出错误:
Now, node is throwing an error when I try to run the app:
Error: .post() requires a callback functions but got a [object Undefined]
saveComment
显然是一个函数,我不明白为什么看不到它.我在saveComment
上方定义了另一个函数,该函数可以完全正确地引用而不会出错,但是将函数内容复制到saveComment
的内容仍然会产生相同的错误.我不知所措,非常感谢您的帮助.
saveComment
is clearly a function, I'm not understanding why it can't see this. I have another function defined right above saveComment
that I'm able to reference completely fine without error, however copying that functions contents to that of saveComment
still yields the same error. I'm at a loss, any help is much appreciated.
每个请求的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 m. gh.
Well...embarrassing answer, saveCommment
is defined with 3 m's in my posts.js
. Ugh.
这篇关于节点+ Express .post路由抛出错误.预期的回调,有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!