【问题标题】:Node + Express .post route throwing error. Expected callback, got objectNode + Express .post 路由抛出错误。预期回调,得到对象
【发布时间】:2013-08-30 20:26:20
【问题描述】:

我目前正在使用 Express + Node 开发一个应用程序。我最近使用以下语法向app.js 文件添加了一个新的.post 路由:

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();
        });
    });
}

【问题讨论】:

  • 能否请您显示模块帖子的导出?
  • @syned -- 发布内容
  • 这真的很尴尬...saveCommentposts.js 中有 3 m。我要去睡午觉了。
  • 尝试使用module.exports...,抱歉耽搁了

标签: node.js express


【解决方案1】:

嗯...令人尴尬的答案,saveCommment 在我的posts.js 中定义为 3 m。呃。

【讨论】:

  • 原始错误信息已经提示,是错字.. toString.call(undefined) === [object Undefined] ;)
【解决方案2】:

您是否查看过其他相关问题?

如:

Understanding callbacks in Javascript and node.js

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

我自己也曾与这个话题争论过,不得不说回调是一个快乐的 node.js 应用程序的基础。

希望这会有所帮助。

【讨论】:

  • 我非常喜欢 JS 中的回调。感谢您的建议:D
【解决方案3】:

我按以下方式编写我的导出。也许这会对你有所帮助:)

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

使用函数:

 var helper = require('helper.js')

 helper.savecomment();

【讨论】:

  • 我马上试一试,回来报告
猜你喜欢
  • 1970-01-01
  • 2022-10-02
  • 2020-10-07
  • 2020-05-10
  • 2021-10-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多