为什么 angular 4 中的 httpclient 假设请求正在发送 json 数据 [英] Why httpclient in angular 4 is assuming that request am sending json data

查看:23
本文介绍了为什么 angular 4 中的 httpclient 假设请求正在发送 json 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular 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

语法错误:在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆