未捕获的SyntaxError:在Response.Body.json的JSON.parse(<anonymous>)的位置0的JSON中出现意外的标记U

时间:2017-02-09 19:31:03

标签: javascript json angular mean-stack

我正在开发一个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)

6 个答案:

答案 0 :(得分:11)

当服务器返回错误(例如500服务器错误)时,我通常会看到这一点。问题是服务器返回纯文本,有时甚至是HTML,然后客户端应用程序试图从中解析JSON,从而抛出错误。我建议打开chrome dev工具,导航到网络选项卡,刷新页面,然后查找有问题的请求,看看从服务器实际返回的是什么。

看起来应该是这样的。我的猜测是右边的文字不是JSON。

Chrome debugger

答案 1 :(得分:5)

“ u”是 undefined 的第一个字母。发生这种情况的原因是期望使用json并获得未定义。

答案 2 :(得分:3)

仔细阅读调用栈;崩溃就在这条线上:

        .map(res=> res.json());

JSON解析器无法理解来自服务器的响应。看看你是否可以找出服务器(POST http://localhost:3000/api/users)发回的响应。响应应该从'U'开始,它不能是有效的JSON。

答案 3 :(得分:1)

return this.http.post('http://localhost:3000/api/users', JSON.stringify(newreg),{headers: headers})
            .map(res=> res.json());

http://localhost:3000/api/users的后端API的返回类型不是JSON,在您的情况下,字符串以字母“U&#39;”开头。确保后端使用res.json("Your text here");返回json数据这是因为你的map函数.map(res=> res.json());期待json响应

答案 4 :(得分:0)

感谢@Jacob Krall指出原因:

我在跟踪代码时遇到了同样的错误

this.http.post(URL, formData).map((res: Response) => res.json()).subscribe(
(success) => {
    alert(success);
},
(error) => alert(error))

原因:我没有从服务器本身发送json数据,因此它正在为行res.json()崩溃

<强>解决方案: 从服务器返回json响应,然后它应该可以正常工作。

取代了以下

return res.send("Upload Completed for " + path);

用,

return res.json("Upload Completed for " + path);

答案 5 :(得分:0)

通常,当您使用箭头功能通过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>)