javascript - 如何在 Angular 5 中发布 XML 主体?

标签 javascript angular ionic-framework ionic3

我目前正在开发一个 Ionic 应用程序,该应用程序应该以 XML 作为主体进行 REST API 调用。我在调用实际使用 XML 进行发布时遇到问题。这是我的 LoginProvider。我使用 DOMParser 将数据解析为 XML,然后再将其发布到 API。

import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Injectable } from '@angular/core';
import * as Constants from '../../services/constants';

@Injectable()
export class LoginProvider {

  constructor(public http: HttpClient) {
  }

  postLogin(username : String, password : String) {
    let parser = new DOMParser();
    let xmlString = "<alm-authentication>  <user>" + username + "</user> <password>" + password + "</password> </alm-authentication>";
    let doc = parser.parseFromString(xmlString, "application/xml");
    console.log(doc);

    let headers = new HttpHeaders()
      .set('Access-Control-Allow-Origin', '*')
      .set('Content-Type', 'application/xml');
    return new Promise(resolve => {
      this.http.post(Constants.API_ENDPOINT + "/authentication-point/alm-authenticate", doc, {headers: headers}).subscribe(data => {
        resolve(data);
      }, err => {
        console.log(err);
      });
    });
  }

}

但是当我检查 Google Chrome 中的发布请求时,我得到以下信息:

enter image description here 请求负载似乎是 JSON 格式,而不是 XML 格式。我怎样才能让它真正发送 XML 文件?

我已经尝试将正文更改为 xml 字符串而不是文件,并更改内容类型,但这仍然给出相同的错误。

我正在使用 Ionic-Angular 版本 3.9.2 和 Angular 版本 5.0.3

最佳答案

let doc = parser.parseFromString(xmlString, "application/xml");

doc 是表示 XML 文档 DOM 的对象。

http.post(Constants.API_ENDPOINT + "/authentication-point/alm-authenticate", doc, {headers: headers})

您正在将 doc 作为参数传递给 http.post

由于您正在传递一个对象,Angular 会尝试将其转换为 JSON。

如果您自己对请求负载进行编码(即您不希望 Angular 将其转换为 JSON),那么您需要传递字符串

传递 xmlString 而不是 doc

关于javascript - 如何在 Angular 5 中发布 XML 主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50039677/

相关文章:

javascript - 如何使用 javascript 获取嵌入在 xml 标签内的值?

javascript - Fancybox 2 自动缩略图

angular - 如何在 Angular 轮询期间保持过滤器完好无损?

javascript - ngrx 订阅时轮询刷新数据

javascript - 如何计算 Angular JS 应用程序(单页应用程序)的页面加载时间

javascript - 警报框未打开

javascript - DataTables header 中的 jQuery UI Datepicker 未生成?

javascript - 正确的错误处理-在javascript/Ionic中

javascript - 如何获取PDF文件的页数?

ios - 在 Ionic 的附件栏中添加键盘隐藏按钮