本文介绍了节点+ Express .post路由抛出错误.预期的回调,有对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用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路由抛出错误.预期的回调,有对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 20:56