为什么angular 4中的httpclient假设请求正在发送json数据 [英] Why httpclient in angular 4 is assuming that request am sending json data
问题描述
我正在使用角度为4的HTTP客户端到返回文本数据的服务器,因此我做了如下操作
I am using angular 4 http client to a server which returns text data so for that I did something like below
this.http.get('assets/a.txt').map((res:Response) =>
res.text()).subscribe((data: any) => {
console.log(data.text());
});
我没有告诉它响应是json格式的任何地方,但仍然引发以下错误
I did not tell it any where that the response is in json format but still it is raising the below error
SyntaxError:Object.parse位置0处的JSON中意外的令牌a ()在XMLHttpRequest.onLoad
SyntaxError: Unexpected token a in JSON at position 0 at Object.parse () at XMLHttpRequest.onLoad
这些人假设响应是json格式:)
On what basis these people assume as the response is in json format :)
推荐答案
默认情况下,新HttpClient
的响应为JSON.如果要获取其他格式的响应,可以通过requestOption
responseType: 'text'
进行设置.以下是有关此实现的更多信息: https://angular.io/guide/http#requesting-non-json-data
The Response of new HttpClient
is JSON by default. If you want to get the response in another format, you can set it via requestOption
responseType: 'text'
. Here is some more information about this implementation: https://angular.io/guide/http#requesting-non-json-data
一个例子:
this.http.get('assets/a.txt', { responseType: 'text' }).map((res:Response) =>
res).subscribe((data: any) => {
console.log(data);
});
这篇关于为什么angular 4中的httpclient假设请求正在发送json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!