Skip to content Skip to sidebar Skip to footer

Uncaught Syntaxerror: Unexpected Token U In Json At Position 0 At Json.parse () At Response.body.json

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 objects

Solution 1:

the "u" there is the first letter of undefined . This is happening as a json is expected and an undefined is obtained.

Solution 2:

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.

Chrome debugger

Solution 3:

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.

Solution 4:

returnthis.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

Solution 5:

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

Answer : 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);

Post a Comment for "Uncaught Syntaxerror: Unexpected Token U In Json At Position 0 At Json.parse () At Response.body.json"