0

I'm currently in the process of getting my feet wet in Angular and experimenting with http.post reponses. I am able to get the response as json without any trouble, however having trouble getting the response as plain text.

This is what I am trying so far to get the response as text:

this.http.post<string>(`http://server/test.php`, 
    { title: 'Angular POST Request Example' }).subscribe(data => {
    console.log(data);
});

test.php simply returns a string such as "hello world"

The browser throws an error object in which I can see the following:

"Unexpected token h in JSON at position 0"

Therefore it looks like it's trying to parse it as json.

How can I force it simply text as the result and not parse as Json?

I've has a look at other solutions which suggest adding headers or even setting "responseType: 'text' as 'json'" in the options (the latter works for me), but I get the impression that the type in the function should cause the function to expect text data as the response.

Kind Regards Musaffar

Musaffar Patel
  • 905
  • 11
  • 26
  • So either responseType: text or wrap your response string in quotes (i.e. json_encode your string in php).. – MikeOne Jul 10 '20 at 18:34
  • Thanks, so is my understanding that part should be causing the response to be parsed as text not true? – Musaffar Patel Jul 10 '20 at 18:37
  • 1
    You can do both. Either tell angular it is a string (instead of default json), or change your response to be json (with quotes). Second option is the best in general.. so on your pho response, just wrap it in json_encode and it should work. – MikeOne Jul 10 '20 at 18:42
  • Well, I've tried the first part (telling angular it is a string by including and did not work as expected. I'll use your second suggestion for now. Thanks – Musaffar Patel Jul 10 '20 at 18:44
  • 1
    Oh right.. no that is not the way to tell Angular it is a string. You’ll have to add {responseType: ‘text’} to your http call as the third param to make that work. – MikeOne Jul 10 '20 at 18:52

0 Answers0