简体   繁体   English

Uncaught SyntaxError: JSON.parse (<anonymous> ) 在 Response.Body.json</anonymous>

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

I am working on an angular2 project.我正在做一个 angular2 项目。 I am stuck with these errors.我被这些错误困住了。 The error occured when I tried to send the JSON objects to the backend.当我尝试将 JSON 对象发送到后端时发生错误。 It may be due the parsing of JSON objects.这可能是由于 JSON 对象的解析。 I am new to angualar, so please do help我是 Angualar 的新手,所以请帮忙

Signup.service.ts注册服务.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)

the "u" there is the first letter of undefined . "u" 是undefined的第一个字母。 This is happening as a json is expected and an undefined is obtained.这是在预期 json 并获得 undefined 时发生的。

I normally see this when the server returns an error (eg a 500 server error).我通常在服务器返回错误(例如 500 服务器错误)时看到这一点。 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.问题是服务器正在返回纯文本,有时甚至是 HTML,然后客户端应用程序试图从中解析 JSON,从而引发错误。 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.我建议打开 chrome 开发工具,导航到网络选项卡,刷新页面,然后查找有问题的请求并查看实际从服务器返回的内容。

It should look something like this.它应该看起来像这样。 My guess is that the text on the right will not be JSON.我的猜测是右边的文本不会是 JSON。

Chrome 调试器

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. JSON 解析器无法理解来自服务器的响应。 See if you can figure out what response the server (the POST to http://localhost:3000/api/users ) is sending back.看看您是否能弄清楚服务器(对http://localhost:3000/api/users的 POST)发回的响应。 The response supposedly starts with 'U' , which cannot be valid JSON.响应应该以'U'开头,这不是有效的 JSON。

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'. http://localhost:3000/api/users的后端 API 有一个不是 JSON 的返回类型,在您的例子中是以字母“U”开头的字符串。 Make sure the back end returns json data by using res.json("Your text here");使用res.json("Your text here");确保后端返回 json 数据。 This is because your map function .map(res=> res.json());这是因为你的地图函数.map(res=> res.json()); is expecting a json response期待一个 json 响应

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);

Actually this is not a frontend problem this is the backend problem.实际上这不是前端问题这是后端问题。 The frontend is expecting a JSON type instead of normal string.前端需要 JSON 类型而不是普通字符串。 For resolving this error, all you need to do is in your backend:要解决此错误,您需要做的就是在后端:

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

This will work:)这会起作用:)

Normally it happens when you use arrow function for fetching data through API and in that you use 'this' keyword.通常,当您使用箭头函数通过 API 获取数据并使用“this”关键字时,就会发生这种情况。 So, arrow function not have its own 'this' So, we got error.所以,箭头函数没有自己的 'this' 所以,我们得到了错误。 This is not the main reason but it is one of them.这不是主要原因,但也是其中之一。

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>) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获到的SyntaxError:JSON中的意外令牌u在JSON.parse的位置0 - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse SyntaxError:JSON中的意外令牌u在JSON.parse( <anonymous> ) - SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 未捕获的SyntaxError:JSON.parse中位置0的JSON中的意外标记a( <anonymous> ) - Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) 未捕获到的SyntaxError:JSON中的意外令牌&lt;在JSON.parse位置0处( <anonymous> ) - Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous>) 未捕获的语法错误:JSON 中的意外令牌 u 在 JSON.parse 的 position 0 处(<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 未捕获的语法错误:JSON 中的意外令牌 u 在 JSON.parse 的 position 0 处(<anonymous> ) at./src/context/AuthContext.js</anonymous> - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) at ./src/context/AuthContext.js VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous> ) - VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) Uncaught SyntaxError: Unexpected token &lt; in JSON at position 0 : at JSON.parse (<anonymous> ) 在对象。<anonymous> - Uncaught SyntaxError: Unexpected token < in JSON at position 0 : at JSON.parse (<anonymous>) at Object.<anonymous> 语法错误:在 JSON 中的意外令牌 u 在 position 0 在 JSON.parse - SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM