angular - 从 Web Api 获取 XML 到 Angular
问题描述
嗨,StackOverflow 用户。
我想获取来自 web api (Asp.net Core) 的字符串
这是我的控制器的代码:
[HttpPost("Xml")]
public string Xml()
{
try
{
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
return _xmlBeautifier.Beautify(reader.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
throw ex;
}
}
这是我的 Angular 代码:
onSubmit() {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'text/xml',
'Content-Type': 'text/xml'
})
};
this.http.post('http://localhost:5000/api/xml/xml', this.xmlForm.controls['XmlData'].value, httpOptions)
.subscribe(res => {
alert('SUCCESS !!');
})
}
我现在正在做的是检查是否正确获取了 XML 字符串。我还没有打印解析后的 XML 的代码,但我已经遇到了错误。
SyntaxError:JSON.parse() 位置 0 处的 JSON 中的意外标记 <
如何修复错误?我已经使用 Postman 测试了 API,它工作正常。
请看下面的截图
更新:
这是完整的错误消息:
HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost:5000/api/xml/xml", ok: false, …
message: "Unexpected token < in JSON at position 0"
stack: "SyntaxError: Unexpected token < in JSON at position 0↵ at JSON.parse (<anonymous>)↵ at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:19139:51)↵ at ZoneDelegate.invokeTask (http://localhost:4200/poly
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure during parsing for http://localhost:5000/api/xml/xml"
name: "HttpErrorResponse"
ok: false
status: 200
statusText: "OK"
url: "http://localhost:5000/api/xml/xml"
而且我还使用了creative-tim的 paper-dashboard-angular 模板
更新:
我上传了示例 web api 和我正在使用的示例角度代码
解决方案
HttpClient 的响应类型的默认值为 JSON。如果您想请求非 JSON 数据,只需将标头设置为以下内容:
this.http.get('...', { responseType: 'text' });
responseType?: 'arraybuffer' | 'blob' | 'json' | 'text'
在你的情况下,它应该是
onSubmit() {
this.http.post('http://localhost:5000/api/xml/xml', { responseType: 'text' })
.subscribe(res => {
alert('SUCCESS !!');
});
}
推荐阅读
- wso2 - 如何编辑 WSO2-IS 的自我注册页面?
- python - Python:将文件夹树中具有给定扩展名的文件复制到另一个文件夹树中:额外的子文件夹复杂性
- android - 我在哪里可以找到将 Android.mk 转换为 Android.bp 的 androidmk 工具?
- php - 如何使用 codeigniter 将月份日期设置为 coloum 表
- python - 由于 SSL 证书 TLSv1.0,pip 失败
- ruby-on-rails-5 - Rails5:包含 json 的固定装置
- hadoop - 如何为 hiveQL 查询设置参数
- elasticsearch - 如何使用 Grok 解析 Logstash 中的日志字符串?
- pentaho - 如何从 pentaho cde 访问水壶中的分页值?
- azure - terraform azure 中相同基础设施的不同实例?