【问题标题】:Retrieve XML from HTTPClient on Angular 5从 Angular 5 上的 HTTPClient 检索 XML
【发布时间】:2017-11-07 13:49:21
【问题描述】:

我正在尝试使用来自 Angular 的 HttpClientSOAP API 检索 xml

这是我的 app.component.html 上的内容:

<input type="submit" value="test POST" (click)="onClickMe()"/>

这是在我的 app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpErrorResponse } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  results: string[];
  constructor(private http: HttpClient) {
    console.log('constructor opened');

  }
  ngOnInit(): void{
    console.log('onInit opened'); 

    }

  onClickMe(){
      var emp = '<<credentials to the webservice>>';
      var login = '<<credentials to the webservice>>';
      var pass = '<<credentials to the webservice>>';
      var id = "<<credentials to the webservice>>";

      const body = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">\r\n  <soap12:Body>\r\n    <Lista xmlns=\"http://GSMMX.WebService/\">\r\n      <Emp>"+emp+"</Emp>\r\n      <Login>"+ login +"</Login>\r\n      <Senha>"+ pass +"</Senha>\r\n      <id>"+ id +"</id>\r\n    </Lista>\r\n  </soap12:Body>\r\n</soap12:Envelope>";
      const url = "<<webserviceURL>>";
      console.log('onClickme opened');

      this.http.post(url, body, {
        headers: new HttpHeaders()
        .set('Content-Type', 'text/xml') 
        .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS') 
        .append('Access-Control-Allow-Origin', '*')
        .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
  }).subscribe(data => {
        console.log(data);

      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      }
    );

  }


}

所以,我使用 Postman 执行了相同的请求,并复制了 url 和 body,就像成功的 POST 一样。我尝试使用 Angular 5 来做到这一点,但它不起作用,它返回以下消息:

Backend returned code 200, body was: [object Object]

有人知道我该怎么做吗?请求收到 200 代码,但响应不正确。

感谢您的帮助!

【问题讨论】:

    标签: xml angular soap angular-httpclient


    【解决方案1】:

    如果您想以文本形式获取响应。您可以尝试添加 { responseType: 'text' }。

    {
            headers: new HttpHeaders()
            .set('Content-Type', 'text/xml') 
            .append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS') 
            .append('Access-Control-Allow-Origin', '*')
            .append('Access-Control-Allow-Headers', "Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Request-Method")
      , responseType:'text'}
    

    【讨论】:

    • 你知道我如何在响应中检索特定值吗?
    • 如果响应是您所说的 XML,那么您必须使用库将 xml 解析为 json。不幸的是,我自己没有使用任何东西,所以我没有推荐。如果响应很小并且只需要一个值,您可以尝试使用正则表达式,但非常不推荐。
    • 我已将其转换为 json,但即使使用 json 我也不知道如何使用它。你知道吗?我正在用它发布一个新问题。
    • @spaceman 响应的正文将是一个字符串,您可以随心所欲地进行操作
    • 我不知道为什么每个人都在谈论 JSON。一旦你设置了responseType: "text",这是正确的,你需要得到你得到的结果——一个包含原始XML的字符串——并创建一个DOMParser,然后调用parseFromString,它会给你一个XMLDocument。没有理由转换为 JSON。
    【解决方案2】:

    如果{ responseType: 'text' } 没有成功,请尝试{ responseType: 'text' as 'text' }

    为了将 XML 响应转换为 JSON,我使用了来自该网站 XMLParser 的基于 Lodash 的脚本。

    您可以使用的另一个解决方案是xml2js

    【讨论】:

      猜你喜欢
      • 2018-05-14
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多