【发布时间】:2018-03-03 21:57:50
【问题描述】:
我正在尝试将 xml 数据转换为 JSON,以便将其返回到我的 Angular 应用程序。
我已经能够获取数据,但我不确定如何转换并返回到 Angular。
我正在使用xml2js解析器插件来转换xml。
node.js
router.get('/courselist', (req, res, next) => {
request("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml", function(error, response, body) {
console.log(body);
parser(body, function (err, result) {
res.json(response);
});
});
解析后的输出是这样的:
{"gesmes:Envelope": {
"$": {
"xmlns:gesmes": "http://www.gesmes.org/xml/2002-08-01",
"xmlns": "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"
},
"gesmes:subject": [
"Reference rates"
],
"gesmes:Sender": [
{
"gesmes:name": [
"European Central Bank"
]
}
],
"Cube": [
{
"Cube": [
{
"$": {
"time": "2017-09-21"
},
"Cube": [
{
"$": {
"currency": "USD",
"rate": "1.1905"
}
},
....
{
"$": {
"currency": "JPY",
"rate": "133.86"
}
},
]
}
]
}
]
}
}
角度服务
getCourseList() {
return this._http.get('./api/course-list').map(
(res: Response) => res.json()
).catch(this.handleError);
}
当我在 Postman 中调用端点时,我可以看到解析后的输出,但在 Angular 中我收到错误,因为我没有返回 JSON 对象。
JSON 中位置 0 处的意外令牌
我一直在寻找解决方案,但找不到适合我的解决方案。 你能告诉我我做错了什么,因为我是 Node.js 的初学者
【问题讨论】:
-
您是否检查了响应以确保它实际上返回了 JSON?
-
它不返回 JSON,我尝试在解析器中
JSON.parse(result)但仍然没有效果