Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json
Uncaught SyntaxError: Unexpected token U in JSON at position 0 at JSON.parse (<anonymous>) at Response.Body.json
我正在做一个 angular2 项目。我被这些错误困住了。当我尝试将 JSON 对象发送到后端时发生错误。这可能是由于 JSON 个对象的解析。我是 angualar 的新手,所以请帮忙
Signup.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
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
<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>
完整的错误信息是
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)
仔细阅读调用堆栈;崩溃发生在这条线上:
.map(res=> res.json());
JSON 解析器无法理解来自服务器的响应。看看您是否可以找出服务器(POST 到 http://localhost:3000/api/users
)发回的响应。响应应该以 'U'
开头,这不是有效的 JSON.
我通常在服务器 returns 出现错误(例如 500 服务器错误)时看到此消息。问题是服务器正在返回纯文本,有时甚至 HTML 然后客户端应用程序试图从中解析 JSON 从而抛出错误。我建议打开 chrome 开发工具,导航到网络选项卡,刷新页面,然后查找有问题的请求并查看实际从服务器返回的内容。
它应该看起来像这样。我猜右边的文字不会是 JSON.
感谢@Jacob Krall 指出原因:
我在执行以下代码时遇到了同样的错误
this.http.post(URL, formData).map((res: Response) => res.json()).subscribe(
(success) => {
alert(success);
},
(error) => alert(error))
原因: 我没有从服务器本身发送 json 数据,所以它在第 res.json()
行崩溃了
解法:
Return json 来自服务器的响应然后它应该工作正常。
替换了以下内容
return res.send("Upload Completed for " + path);
有,
return res.json("Upload Completed for " + path);
return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
.map(res=> res.json());
http://localhost:3000/api/users 处的后端 API 有一个 return 类型,它不是 JSON,在您的例子中,字符串以字母 'U' 开头。使用 res.json("Your text here");
确保后端 returns json 数据 这是因为您的地图函数 .map(res=> res.json());
需要 json 响应
"u" 有 undefined 的第一个字母。这是因为预期 json 并且获得了未定义。
通常当您使用箭头函数通过 API 获取数据时会发生这种情况,因为您使用 'this' 关键字。
所以,箭头函数没有自己的 'this' 所以,我们得到了错误。
这不是主要原因,但也是其中之一。
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>)
我正在做一个 angular2 项目。我被这些错误困住了。当我尝试将 JSON 对象发送到后端时发生错误。这可能是由于 JSON 个对象的解析。我是 angualar 的新手,所以请帮忙
Signup.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
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
<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>
完整的错误信息是
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)
仔细阅读调用堆栈;崩溃发生在这条线上:
.map(res=> res.json());
JSON 解析器无法理解来自服务器的响应。看看您是否可以找出服务器(POST 到 http://localhost:3000/api/users
)发回的响应。响应应该以 'U'
开头,这不是有效的 JSON.
我通常在服务器 returns 出现错误(例如 500 服务器错误)时看到此消息。问题是服务器正在返回纯文本,有时甚至 HTML 然后客户端应用程序试图从中解析 JSON 从而抛出错误。我建议打开 chrome 开发工具,导航到网络选项卡,刷新页面,然后查找有问题的请求并查看实际从服务器返回的内容。
它应该看起来像这样。我猜右边的文字不会是 JSON.
感谢@Jacob Krall 指出原因:
我在执行以下代码时遇到了同样的错误
this.http.post(URL, formData).map((res: Response) => res.json()).subscribe(
(success) => {
alert(success);
},
(error) => alert(error))
原因: 我没有从服务器本身发送 json 数据,所以它在第 res.json()
解法: Return json 来自服务器的响应然后它应该工作正常。
替换了以下内容
return res.send("Upload Completed for " + path);
有,
return res.json("Upload Completed for " + path);
return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
.map(res=> res.json());
http://localhost:3000/api/users 处的后端 API 有一个 return 类型,它不是 JSON,在您的例子中,字符串以字母 'U' 开头。使用 res.json("Your text here");
确保后端 returns json 数据 这是因为您的地图函数 .map(res=> res.json());
需要 json 响应
"u" 有 undefined 的第一个字母。这是因为预期 json 并且获得了未定义。
通常当您使用箭头函数通过 API 获取数据时会发生这种情况,因为您使用 'this' 关键字。 所以,箭头函数没有自己的 'this' 所以,我们得到了错误。 这不是主要原因,但也是其中之一。
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>)