在JSON的第0个位置发现了意外的U标记,无法解析。位于Response.Body.json中的JSON.parse函数。

18

我正在开发一个Angular2项目,遇到了一些错误。当我尝试将JSON对象发送到后端时出现了错误。这可能是由于JSON对象的解析引起的。我对Angular比较新,请帮忙。

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='';
      });     
  } 
 }

注册组件.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)

响应不是 JSON,而是可能以“U”字母开头的纯文本错误/警告消息。您需要检查网络控制台以检查对 http://localhost:3000/api/users 的响应。 - F.Igor
7个回答

37

"u" 这里是 undefined 的首字母。这是由于期望得到的是一个JSON对象, 但实际却得到了一个未定义的值。


30
我通常在服务器返回错误时看到这个问题(例如500个服务器错误)。问题在于服务器返回纯文本或有时甚至是HTML,然后客户端应用程序试图从中解析JSON,因此抛出错误。我建议打开Chrome开发工具,导航到网络选项卡,刷新页面,然后查找相关请求并查看服务器实际返回的内容。
它应该看起来像这样。我猜右侧的文本不会是JSON。 Chrome debugger

3
服务器返回的文本信息是“用户已创建”,这就是导致错误发生的原因。非常感谢。 - Karthik
现在它返回了JSON对象,但是另一个错误出现了:“无法读取未定义的属性'push'”。返回的JSON对象是{"message":"success"}。那么为什么会出现这个错误? - Karthik

5

仔细阅读调用堆栈,崩溃发生在这行代码上:

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

JSON解析器无法理解服务器的响应。请检查一下服务器(POST到http://localhost:3000/api/users)返回的响应内容。据说响应以'U'开头,这不可能是有效的JSON。


服务器发送的是纯文本。已经修正了错误。谢谢。 - Karthik

2
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”开头的字符串。请确保后端使用res.json("Your text here");返回JSON数据。这是因为您的map函数.map(res=> res.json());期望得到JSON响应。


1

感谢@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);

with,

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

0

实际上这不是前端的问题,而是后端的问题。前端期望的是JSON类型而不是普通字符串。要解决这个错误,你只需要在后端进行以下操作:

res.json("Whatever you want to send")

这个会起作用的 :)


-2
通常情况下,当您使用箭头函数通过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>) 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接