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

120,060

Solution 1

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.

It should look something like this. My guess is that the text on the right will not be JSON.

Chrome debugger

Solution 2

the "u" there is the first letter of undefined . This is happening as a json is expected and an undefined is obtained.

Solution 3

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.

Solution 4

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'. 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

Solution 5

Thanks @Jacob Krall for pointing out the reason:

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

Solution: Return json response from server then it should work fine.

replaced the following

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

with,

return res.json("Upload Completed for " + path);
Share:
120,060
Karthik
Author by

Karthik

Fullstack developer. Works remotely.

Updated on July 09, 2022

Comments

  • Karthik
    Karthik almost 2 years

    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

    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>
    

    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)
    
  • Karthik
    Karthik about 7 years
    The server was responding with a text saying "User Created". That's why the error occurred. Thanks a lot
  • Karthik
    Karthik about 7 years
    Server was sending plain text. Corrected the errors. Thank you
  • Karthik
    Karthik about 7 years
    It now gives back json object but another error is occuring "Cannot read property 'push' of undefined". The JSON onject returning is {"message":"success"}. Then why is this error occurring?