【问题标题】:Unable to receive XML response with the help of angular 8 HttpClient无法在 Angular 8 HttpClient 的帮助下接收 XML 响应
【发布时间】:2019-10-24 07:18:46
【问题描述】:

服务器正在向我发送 XML 响应,但我无法使用 HttpClient angular 8 获取它。在 Postman 中,它工作正常。

尝试将 responseType 设为“blob”。尝试使用 HttpOptions。尝试使用 header Allow-Encoding gzip 等。

let url = "My server URL";
let body = "My xml content in string";
const headers = new HttpHeaders()
      .set('Accept', 'text/xml')
      .set('Content-Type', 'text/xml')
      .set('userid', 'xxxx')
      .set('password', 'xxxx')
      .set('authkey', 'xxxxxxxxxxxxxxx');

this.httpClient.post(url, body, {headers: headers, responseType: 'text'})
.subscribe(resonse => {
      console.log(resonse);
    }, err => {
      console.error(err);
    });

预期:XML 响应 实际:空字符串("")

【问题讨论】:

  • 尝试将其作为纯文本发送,然后解析为 xml
  • 可能是网址不完全相同?你能分享一下浏览器的开发工具输出吗?
  • @brandt.codes Cross-Origin Read Blocking (CORB) blocked cross-origin response https://xxxxxx.org/API/xmlapi2.aspx with MIME type text/plain. See https://www.chromestatus.com/feature/5629709824032768 for more details.
  • 这是一个 CORS (de.wikipedia.org/wiki/Cross-Origin_Resource_Sharing) 问题。您的代码是正确的。

标签: angular


【解决方案1】:

这是因为 Chrome 而不是因为 Angular。 Chrome 已决定该响应不可信任并已替换为 null。您可以尝试使用 Firefox,它应该没问题。要求您的后端在响应中添加“Access-Control-Allow-Origin: *”标头,这可能会解决问题,但对我来说并不总是有效。

查看https://www.chromium.org/Home/chromium-security/corb-for-developers 了解更多详情。

【讨论】:

    【解决方案2】:

    因为responseType 可能是:

    responseType: 'arraybuffer' | 'blob' | 'json' | 'text'
    

    服务器的预期响应类型。

    这用于在返回之前适当地解析响应 给被请求者。

    然后,如果您想构造一个将正文解释为文本字符串并将响应作为字符串值返回的 CRUD 请求,您可以查看此文档 - HttpClient Overload #3

    响应将是:

    Observable<string>: 响应的 Observable,带有响应 字符串类型的主体。

    然后在发送请求后根据需要解析为xml。

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 2013-11-07
      相关资源
      最近更新 更多