Javascript Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.jso
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42145287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json
提问by Karthik
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. I am new to angualar, so please do help
我正在处理 angular2 项目。我被这些错误困住了。当我尝试将 JSON 对象发送到后端时发生错误。这可能是由于 JSON 对象的解析。我是angularar的新手,所以请帮忙
Signup.service.ts
注册.service.ts
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map' ;
@Injectable()
export class SignupService{
constructor (private http: Http){}
insertform(newreg: any ){
console.log();
var headers = new Headers ();
headers.append('Content-Type','application/json');
return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
.map(res=> res.json());
}
}
signup.component.ts
注册.component.ts
import { Component, AfterViewInit } from '@angular/core';
import {SignupService} from '../../services/signup.service';
import {Signup} from '../../../signup';
declare var $: any;
@Component({
moduleId: module.id,
selector: 'signup',
templateUrl: 'signup.component.html',
providers: [SignupService]
})
export class SignupComponent {
datas: Signup[];
data: any;
first_name: string;
last_name: string;
address: string;
email: string;
pwd:string;
pwdcnf:string;
phone:number;
constructor(private signupService: SignupService){ };
ngAfterViewInit() {
$('#textarea1').trigger('autoresize');
};
regformSubmit(event: any){
event.preventDefault();
var newreg = {
first_name: this.first_name,
last_name: this.last_name,
email: this.email,
address: this.address,
phone: this.phone,
pwd:this.pwd,
pwdcnf:this.pwdcnf
};
this.signupService.insertform(newreg)
.subscribe (data => {
this.datas.push(data);
this.first_name='';
this.last_name ='';
this.email='';
this.address='';
this.phone=0;
this.pwd='';
this.pwdcnf='';
});
}
}
signup.component.html
注册.component.html
<div class="container light-blue lighten-5">
<form class="col s12" (ngSubmit)="regformSubmit($event)">
<div class="row">
<div class="input-field col s6">
<input id="first_name" type="text" class="validate" [(ngModel)]="first_name" name="first_name" required>
<label for="first_name">First Name</label>
</div>
<div class="input-field col s6">
<input id="last_name" type="text" class="validate" [(ngModel)]="last_name" name="last_name" required>
<label for="last_name">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" [(ngModel)]="address" name="address" required></textarea>
<label for="disabled">Address</label>
</div>
</div>
<div class="row ">
<div class="input-field col s5">
<input id="password" type="password" class="validate" [(ngModel)]="pwd" name="pwd" required>
<label for="password">Password</label>
</div>
<div class="input-field col s5 offset-s2">
<input id="password1" type="password" class="validate" [(ngModel)]="pwdcnf" name="pwdcnf" required>
<label for="password1">Confirm password</label>
</div>
</div>
<div class="row">
<div class="input-field col s5">
<input id="email" type="email" class="validate" [(ngModel)]="email" name="email" required>
<label for="email">Email</label>
</div>
<div class="input-field col s5 offset-s2">
<input id="password2" type="number" class="validate" [(ngModel)]="phone" name="number" required>
<label for="password2">Phone</label>
</div>
</div>
<div class="row">
<div class="input-field col s4 offset-s5">
<button class="btn waves-effect waves-light" type="submit" name="action">Submit
<i class="material-icons right">send</i>
</button>
</div>
</div>
</form>
</div>
<style>
.ng-invalid {
border-bottom-color: red;
}
</style>
The full error message is
完整的错误信息是
EXCEPTION: Unexpected token U in JSON at position 0
ORIGINAL STACKTRACE:
yntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
Uncaught SyntaxError: Unexpected token U in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.umd.js:777)
at MapSubscriber.eval [as project] (signup.service.ts:13)
at MapSubscriber._next (map.ts:75)
at MapSubscriber.Subscriber.next (Subscriber.ts:95)
at XMLHttpRequest.onLoad (http.umd.js:1180)
at ZoneDelegate.invokeTask (zone.js:275)
at Object.onInvokeTask (core.umd.js:3971)
at ZoneDelegate.invokeTask (zone.js:274)
at Zone.runTask (zone.js:151)
at XMLHttpRequest.ZoneTask.invoke (zone.js:345)
回答by Shashank Bodkhe
the "u" there is the first letter of undefined. This is happening as a json is expected and an undefined is obtained.
“u”是undefined的第一个字母。发生这种情况是因为预期 json 并且获得了 undefined。
回答by mparis
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.
当服务器返回错误(例如 500 服务器错误)时,我通常会看到这一点。问题是服务器返回纯文本,有时甚至是 HTML,然后客户端应用程序试图从中解析 JSON,从而引发错误。我建议打开 chrome 开发工具,导航到网络选项卡,刷新页面,然后查找有问题的请求并查看服务器实际返回的内容。
It should look something like this. My guess is that the text on the right will not be JSON.
它应该看起来像这样。我的猜测是右边的文本不会是 JSON。
回答by Jacob Krall
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.
JSON 解析器无法理解来自服务器的响应。看看您是否能弄清楚服务器(POST 到http://localhost:3000/api/users)正在发回什么响应。响应应该以 开头'U',它不能是有效的 JSON。
回答by 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/usershas 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
位于http://localhost:3000/api/users的后端 API的返回类型不是 JSON,在您的情况下为以字母“U”开头的字符串。确保后端通过使用返回 json 数据res.json("Your text here");这是因为您的 map 函数.map(res=> res.json());需要一个 json 响应
回答by immirza
Thanks @Jacob Krall for pointing out the reason:
感谢@Jacob Krall 指出原因:
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()
原因:我没有从服务器本身发送 json 数据,所以它在线路上崩溃了res.json()
Solution:Return json response from server then it should work fine.
解决方案:从服务器返回 json 响应,然后它应该可以正常工作。
replaced the following
替换了以下内容
return res.send("Upload Completed for " + path);
with,
和,
return res.json("Upload Completed for " + path);


