从Angular 5的HTTPClient检索XML

6
我将为您翻译此内容:

我正在尝试使用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进行了相同的请求,并复制了成功POST的url和body。我尝试使用Angular 5进行操作,但它无法正常工作,返回以下消息:

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

有人知道如何让这个工作吗?请求得到了200代码,但响应并没有正确地返回。

非常感谢任何帮助!

2个回答

5

如果你想获得文本形式的响应,可以尝试添加{ 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'}

你知道我如何在响应中检索特定的值吗? - spaceman
如果响应确实是XML格式,那么你需要使用一个库将其解析成JSON格式。不幸的是,我自己没有使用过这样的库,所以无法提供推荐。如果响应很小且您只需要一个值,则可以尝试使用正则表达式,但这是极不推荐的。 - Sameh Awad
我已将其转换为JSON格式,但即使是JSON格式,我也不知道如何使用它。你知道吗?我会发布一个新的问题来询问。 - spaceman
@spaceman 响应的主体是一个字符串,您可以随心所欲地处理它。 - Ruan Mendes
我不知道为什么每个人都在谈论JSON。一旦你设置了 responseType: "text",这是正确的,你需要获取结果——一个包含原始XML的字符串——并创建一个DOMParser,然后调用parseFromString,这将给你一个XMLDocument。没有理由转换为JSON。 - Coderer

5
如果{ responseType: 'text' }无法解决问题,请尝试使用{ responseType: 'text' as 'text' }
为了将XML响应转换为JSON,我使用了这个网站XMLParser上基于Lodash的脚本。
另一个你可以使用的解决方案是xml2js

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接