angular - 如何在 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);
错误信息是
“意外的令牌。需要构造函数、方法、访问器或属性。”
解决方案
希望您使用的是 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);
推荐阅读
- python - 如何绘制超过 1000 个字典键和值
- mysql - 在 wp_usermeta 中没有特定 meta_key 的 Wordpress 中的 MYSQL 查询
- draw.io - 使用 Draw.io embed 限制默认模板
- marklogic - MarkLogic Data Hub 中的 XML 或 JSON 是首选吗?
- django - 如何通过 django sendmail 发送图片
- terraform - 使用相同代码应用第二个 terraform 后,将删除 api-gateway 集成响应设置
- python - Count If with Condition Pandas DataFrame
- azure - 我可以从 Power BI 数据流实体自动刷新我的 Azure SQL 表吗?
- flutter - 在 anchestor 中找不到提供程序
- spring-cloud - Spring Cloud Stream v3.0.2.RELEASE 在运行 Spring Cloud Kafka 测试时给我错误