Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json

杀马特。学长 韩版系。学妹 提交于 2019-12-06 04:48:40

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.

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.

Manoj
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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!