Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why httpclient in angular 4 is assuming that request am sending json data

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());
});

I did not tell it any where that the response is in json format but still it is raising the below error

SyntaxError: Unexpected token a in JSON at position 0 at Object.parse () at XMLHttpRequest.onLoad

On what basis these people assume as the response is in json format :)

like image 486
user2753523 Avatar asked May 03 '26 23:05

user2753523


1 Answers

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

An example:

this.http.get('assets/a.txt', { responseType: 'text' }).map((res:Response) => 
res).subscribe((data: any) => {
  console.log(data);
});
like image 184
Gregor Doroschenko Avatar answered May 05 '26 13:05

Gregor Doroschenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!