1

When I try post data to my server, I'm getting the error:

SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse...

I am not using JSON.parse() so I assume Angulars Http.post() automatically does this?

When I try console.log(JSON.parse(data)), I'm getting:

SyntaxError: Unexpected token o in JSON at position 1...

When I send the data from Postman - works perfectly fine, no errors and the server receives it.

When I send the data in a fetch() api request - also works perfectly fine, no errors whatsoever.

So, this only occurs when I try use angulars HTTP lib and try to post. Below is an example of some JSON data I send and an example of my http post.

Thanks in advance! This has been driving me crazy!

{"tutorialName":"cvbcvbxcvbxcvbbxcv","sections":[]}
this.http.post("http://127.0.0.1:5000/endpoint", JSON.stringify(this.tutorialForm.value)).subscribe();
Ale8k
  • 153
  • 1
  • 12
  • 4
    Possible duplicate of [HTTPClient POST tries to parse a non-JSON response](https://stackoverflow.com/questions/50826531/httpclient-post-tries-to-parse-a-non-json-response) – edkeveked Sep 09 '19 at 17:24
  • You either have to set the response type in angular side this way `responseType: 'text'` or on the server side encode the data as json – edkeveked Sep 09 '19 at 17:26
  • @Ale8k can you post response as well to find out where you have got error in response. – Sanoj_V Sep 09 '19 at 17:37
  • Yeah sure will try now Ok, so I sent JSON response back from the server and it was happy, which header to I need to add to my post to expect a status in Angular? Thank you so much @Sanoj_V – Ale8k Sep 09 '19 at 17:38

1 Answers1

4

Turns out the solution was the response type option on HTTP.post in Angular, it didn't align up with the server (https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType for types) and defaults to JSON. Thank you to all who answered!

Ale8k
  • 153
  • 1
  • 12