首页 > 解决方案 > 访问自己的api时无法读取未定义的属性

问题描述

我正在尝试将我自己的express.jsapi 与 nodejs 一起使用。问题是它有效,但它给出了错误,我无法访问请愿书的结果。这是我的代码:

路线.js:

app.post('/petition/:id', function(req, res) {
    console.log("ID: ", req.params.id);
    if (!req.params.id) {
        return res.send({"status": "error", "message": "Chooser id needed"});
    }
    else {
        indicoUtils.indicoPositivosNegativos(req.params.id).then(function(result) {
            return res.send({"result": result});
        })
    }
})

计算器.js:

var indicoPositivosNegativos = function (chooserId) {
    var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
    TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
        Promise.all(
            tweets.map(({ _id, tweet }) =>
                indico.sentiment(tweet).then(result =>
                    TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
                        .then( updated => { console.log(updated); return updated })
                )
            )
        )
    )
};

我正在用 Postman 进行测试,它显示了错误:

TypeError:无法读取未定义的属性.then

标签: javascriptnode.jsexpress

解决方案


这基本上意味着您尝试调用 .then 函数的对象之一是未定义的。

具体来说,对象 indicoUtils.indicoPositivosNegativos(req.params.id) 应该是一个承诺,但您的函数 indicoPositivosNegativos 不会返回一个承诺。实际上,您的函数不会返回任何内容,因此 .then 会在未定义的值上调用。

解决方案很简单,您必须在calculator.js 上添加一个return 语句才能返回这样的promise:

var indicoPositivosNegativos = function (chooserId) {
    var TweetModel = mongoose.model('Tweet'.concat(chooserId), Tweet.tweetSchema);
    return TweetModel.find({},{ _id: 1, tweet: 1}).then(tweets =>
        Promise.all(
            tweets.map(({ _id, tweet }) =>
                indico.sentiment(tweet).then(result =>
                    TweetModel.findOneAndUpdate({ _id }, { indicoPositivoNegativo: result }, { new: true })
                        .then( updated => { console.log(updated); return updated })
                )
            )
        )
    )
};

推荐阅读