Angular 4.3.4 httpclient返回null作为订阅,但我在网络上得到了有效的http响应



我正在尝试访问一个提供XML数据的Web服务。过去,我使用节点服务器back并且可以毫无问题地调用外部Web服务。

现在我的目标是使用新的 httpclient 从我的 Angular 4.3.4 应用程序直接访问外部 Web 服务。

如果我尝试通过从本地主机休息服务获取数据,一切正常。但是,如果我尝试获取外部服务,我的行为很奇怪: 在订阅中,我总是从服务中获得 NULL 作为返回值,但如果我查看内部的网络通信,如果我在 chrome 中查看数据,我看到数据被正确传输,状态为 200。

httpClient.post(
'http://www.fivb.org/Vis2009/XmlRequest.asmx',
'Request=<Requests Username="Guest" >' +
'<Request Type="GetBeachTournamentList" ' +
'Fields="Code No Name CountryCode Gender NoEvent Type">' +
'<Filter Types="36" />' +
'</Request>' +
'</Requests>',
{ headers: new HttpHeaders()
.set('Accept', 'application/xml')
.set('Content-Type', 'application/x-www-form-urlencoded;')
})
.subscribe(
data => {
// here I get null
console.log(data);
},
err => {
console.log(err);
}
);

如果有人有想法就太好了

提供完整样品

我的猜测是您应该responseType设置为text,内部请求选项。

httpClient.post(
'http://www.fivb.org/Vis2009/XmlRequest.asmx',
`Request=
<Requests Username="Guest" >
<Request Type="GetBeachTournamentList" Fields="Code No Name CountryCode Gender NoEvent Type">
<Filter Types="36" />
</Request>
</Requests>`,
{ headers: new HttpHeaders()
.set('Accept', 'application/xml')
.set('Content-Type', 'application/x-www-form-urlencoded;'),
responseType: 'text' //<== set here to receive text/xml response.
}
)

默认情况下,HttpClient 将响应解析为 JSON 并返回适当的 JavaScript 对象。但在您的情况下,响应是 XML 而不是 JSON,因此此逻辑失败。

根据请求非 JSON 数据,需要在第二个参数中指定responseType: 'text'才能获取原始文本响应:

let options = { 
responseType: 'text',
headers: new HttpHeaders()
.set('Accept', 'application/xml')
.set('Content-Type', 'application/x-www-form-urlencoded;')
}
httpClient.post(url, data, options)

相关内容

最新更新