首页 > 解决方案 > 如何在 Angular 7 中对 Web 服务进行 POST API 调用?

问题描述

我需要将数据发送到文本挖掘 Web 服务以从中提取元数据。在遵循文档之后,我提出了以下代码,但在第一行出现 var 错误。

我尝试用 data:string 替换 var data 来声明变量,但它没有用。

var data = "<?xml version=\"1.0\" *XML Data*";

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
    }
});

xhr.open("POST", "http://localhost:40002/");
xhr.setRequestHeader("cookie", "JSESSIONID=1gsl3g26oa2l71jmauv312tub9");
xhr.setRequestHeader("content-type", "application/xml");

xhr.send(data);

错误信息是

“意外的令牌。需要构造函数、方法、访问器或属性。”

标签: angularrest

解决方案


希望您使用的是 Angular 2+ 版本。以下是步骤

//import the HttpClient
import { HttpClient } from '@angular/common/http';

//initialize the same in the constructor
constructor(private http: HttpClient){}

//Use the HttpClient instance http to post the call

var fd = new FormData();
   let username = environment.username;
   let password = environment.password;
   let authToken = btoa(username + ":" + password);

   const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'application/vnd.emc.documentum+json',
        'Authorization': 'Basic ' + authToken,
      })
    };

    fd.append('data', JSON.stringify(docObj));
    this.http.post(URL, fd, httpOptions);

推荐阅读