gpt4 book ai didi

javascript - NODE.js无法使用reSTLer获得的restful数据

转载 作者:行者123 更新时间:2023-12-03 10:33:09 25 4
gpt4 key购买 nike

我正在将 ReSTLer 与 NODE.JS 结合使用来从实时提要中获取数据。如果我只想将整个提要显示到屏幕上,它会很好地工作,但是我想实际抓取提要并将其过滤下来,只发出需要的内容。

这是我的 API 中有效的代码片段

app.get('/cis/public/:crs', function (req, res) {

fullpath = 'http://(domain)/timetables/search_crs.php?crs='+req.params.crs;

rest.get(fullpath).on('complete', function(result) {
if (result instanceof Error) {
console.log('Error:', result.message);
this.retry(1000); // try again after 1 sec
} else {
res.send(result);
}
});

});

这会在屏幕上显示完整的提要,尽管格式不符合我的预期。

这是我想要做的一个示例,如果我正在使用本地 JSON 文件,则效果很好。例如,如果我输入类似

的内容

var results = JSON.parse(fs.readFileSync('./data/ppm.json', 'utf8'));

但是,当使用以下格式的 Restful 时,我会失败

app.get('/cis/public/:crs', function (req, res) {

fullpath = 'http://(domain)/timetables/search_crs.php?crs='+req.params.crs;

rest.get(fullpath).on('complete', function(result) {
if (result instanceof Error) {
console.log('Error:', result.message);
this.retry(1000); // try again after 1 sec
} else {
var National = result.GetStationBoardResult.locationName;
res.send(National);
}
});

});

抛出的错误是

            var National = result.GetStationBoardResult.locationName;
^
TypeError: Cannot read property 'locationName' of undefined

如何在 Node 内使用从 ReSTLer 获取的数据,而不仅仅是在屏幕上显示。

这是返回的 JSON 的示例(顶部部分)

{
"GetStationBoardResult": {
"generatedAt": "2015-03-18T10:49:36.9120348+00:00",
"locationName": "Swindon",
"crs": "SWI",
"platformAvailable": true,
"trainServices": {

谢谢

编辑:这是最后一段代码,现在为我提供了有用且可用的 JSON 来使用。

app.get('/cis/public/:crs/:total', function (req, res) {

fullpath = 'http://(domain)/timetables/search_crs.php?crs='+req.params.crs+'&total='+req.params.total;

rest.get(fullpath).on('complete', function(result) {
if (result instanceof Error) {
console.log('Error:', result.message);
this.retry(1000); // try again after 1 sec
} else {
var Results = JSON.parse(result);
res.send(Results);
}
});

});

我现在可以使用结果做额外的事情。并将 JSON 分解为更多可用(和过滤)信息

最佳答案

console.log 时会发生什么

result

根据错误,您的对象结果没有名为

的属性
GetStationBoardResult

编辑:由于结果是字符串而不是对象,因此将使用以下方法解决:

var National = JSON.parse(result).GetStationBoardResult.locationName;

关于javascript - NODE.js无法使用reSTLer获得的restful数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29119499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com