I am working on an angular2 project. I am stuck with these errors. The error occured when I tried to send the JSON objects to the backend. It may be due the parsing of JSON obje
I normally see this when the server returns an error (e.g. a 500 server error). The problem is that the server is returning plain text or sometimes even HTML and then the client app is trying to parse JSON from it thus throwing the error. I would recommend opening the chrome dev tools, navigating to the network tab, refreshing the page, and then look for the request in question and see what is actually getting returned from the server.
It should look something like this. My guess is that the text on the right will not be JSON.
Normally it happens when you use arrow function for fetching data through API and in that you use 'this' keyword. So, arrow function not have its own 'this' So, we got error. This is not the main reason but it is one of them.
fetch.addEventListener('load',()=> {
const [delta] = JSON.parse(this.responseText);
console.log(delta);
//Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>)
the "u" there is the first letter of undefined . This is happening as a json is expected and an undefined is obtained.
Read the call stack closely; the crash is on this line:
.map(res=> res.json());
The JSON parser is failing to understand the response from the server. See if you can figure out what response the server (the POST to http://localhost:3000/api/users
) is sending back. The response supposedly starts with 'U'
, which cannot be valid JSON.
return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
.map(res=> res.json());
The backend API at http://localhost:3000/api/users has a return type that is not JSON, in your case String beginning with the letter 'U'. Make sure the back end returns json data by using res.json("Your text here");
This is because your map function .map(res=> res.json());
is expecting a json response
Thanks @Jacob Krall for pointing out the reason:
I was getting the same error for following code
this.http.post(URL, formData).map((res: Response) => res.json()).subscribe(
(success) => {
alert(success);
},
(error) => alert(error))
Reason: I was not sending json data from server itself so it was crashing for line res.json()
Solution: Return json response from server then it should work fine.
replaced the following
return res.send("Upload Completed for " + path);
with,
return res.json("Upload Completed for " + path);