【发布时间】:2019-03-07 15:12:42
【问题描述】:
直到最近,我一直在使用node request 模块获取 XML 数据,然后通过 XML 到 JSON 转换器运行该 XML。我偶然发现,如果我将 json: true 设置为一个选项(即使知道端点返回 XML,而不是 JSON),我实际上会返回 JSON:
var request = require('request');
var options = { gzip: true, json: true, headers: { 'User-Agent': 'stackoverflow question (https://stackoverflow.com/q/52609246/4070848)' } };
options.uri = 'https://api.met.no/weatherapi/locationforecast/1.9/?lat=40.597&lon=-74.26';
request(options, function (error, response, body) {
console.log(`body for ${options.uri}: ${JSON.stringify(body)}`);
});
上述调用返回 JSON,而 raw URL 实际上是发送 XML。果然,json: false返回的数据是XML:
var request = require('request');
var options = { gzip: true, json: true, headers: { 'User-Agent': 'stackoverflow question (https://stackoverflow.com/q/52609246/4070848)' } };
options.uri = 'https://api.met.no/weatherapi/locationforecast/1.9/?lat=40.597&lon=-74.26';
options.json = false; // <<--- the only difference in the request
request(options, function (error, response, body) {
console.log(`body for ${options.uri}: ${body}`);
});
所以我认为“这很方便”,直到我用 different URL that also returns XML 尝试了同样的技巧,在这种情况下,尽管使用了相同的请求选项,但返回的数据仍然是 XML:
var request = require('request');
var options = { gzip: true, json: true, headers: { 'User-Agent': 'stackoverflow question (https://stackoverflow.com/q/52609246/4070848)' } };
options.uri = 'https://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?whichClient=NDFDgen&lat=40.597&lon=-74.26&product=time-series&temp=tempSubmit=Submit';
request(options, function (error, response, body) {
console.log(`body for ${options.uri}: ${body}`);
});
这里有什么区别?如何获得后一个请求以 JSON 格式返回数据(这样我就可以避免自己将 XML 转换为 JSON 的步骤)?也许第一个示例中的端点可以检测到请求 JSON 并且它确实返回 JSON 而不是 XML?
EDIT 奇怪的是,第一个请求现在返回 XML 而不是 JSON,即使使用 json: true。所以也许这种行为归结为从端点发送的内容,即使在我几个小时前发布后他们已经改变了这一点
【问题讨论】:
-
他们在看着你! :)
-
绝对有可能,因为我特意在用户代理中添加了这篇文章的链接:)
-
好吧,如果你还在看这篇文章
met.nodevs,把它改回来!在 REST API 世界中,提供资源的多种表示形式并区分 Accept 和 Content-Type 标头是非常标准的东西。
标签: json node.js xml node-request