javascript - 访问自己的api时无法读取未定义的属性
问题描述
我正在尝试将我自己的express.js
api 与 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
解决方案
这基本上意味着您尝试调用 .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 })
)
)
)
)
};
推荐阅读
- wso2 - 某些客户端(用户)无法调用 API。(发布者,devportal 在试用选项卡上)
- matlab - 声明 Simulink 模型变量的 Matlab 脚本
- javascript - 在 node.js 中,提交表单后,如何提示成功消息然后跳转到主页?
- c# - Visual Studio 无法打开 Windows 窗体应用程序设计器
- c# - 在 C# 函数中打开 VB.NET 表单
- sql - 如何在 sql [Oracle] 中分组并查找最大值
- google-play - 我可以在已发布的版本中添加国家/地区吗?
- r - 删除 var2 = x 的行,其中 var1=0 且下面的行具有 var1=1
- python - R相当于在Python中对空列表执行操作?
- android - 新的 Jetpack 分页库使应用程序崩溃 - 新