[英]node.js and telegram bot
我需要使用電報漫游器來調用網站的路由。 在該網站的routes.js
,我有:
app.get('/api/getalert', getAlert);
和
var getAlert = function(req, res) {
var id = req.query.id;
Alert.find({})
.sort({
"alertStatus.date": -1
})
.limit(1)
.exec(
function(err, alert) {
if (err) {
res.status(500).send(err)
};
console.log(JSON.stringify(alert, null, 4));
res.json(alert);
});
};
在電報機器人中,我有:
bot.on("/alarm", msg => {
let fromId = msg.from.id;
var options = {
host: "my.website",
port: 3333,
path: "/api/getalert"
};
var callback = function(res) {
res.on("data", function(data) {
console.log('data is '+data);
console.log('name is: '+data.name);
});
}
var req = http.get(options, callback)
.on('error', function(e) {
console.error(e);
});
)};
bot.connect();
console.log(data)
的結果與此類似:
data is
[{
"_id":"585d08455733bb63a19b0b4d",
"name":"Alert",
"description":"Alert description",
"address":"an_address ",
"__v":0,
"alertStatus":
[{"_id":"585d08455733bb63a19b0b4c",
"date":"2016-12-23T11:19:33.608Z",
"status":1
}],
"users":[42711895,85811757],
"range":1000,
"position":{"lat":11,"lng":12}
}]
但。
使用console.log(data[0])
它僅輸出91
。
使用console.log(data.name)
它輸出undefined
。
我做錯了什么?
我想我有一個解決方案...我接收大塊數據,然后合並單個大塊,然后在'end'
將大塊連接起來並進行解析:
var callback = function(res) {
var dataChunks = [];
res.on('data', function(chunk) {
dataChunks.push(chunk);
})
.on('end', function() {
//obj will contain the objects received
var obj = Buffer.concat(dataChunks);
//all objects in JSON format
var stringObj = JSON.parse(obj);
//test to check if it works
console.log(stringObj[0].users);
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.