Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected end of JSON input in Http get request from Angular 2 to Codeigniter

Angular 2 with Codeigniter Hello World Program running perfectly. But I am getting error "Unexpected end of JSON input" while sending Http get request from Angular 2 to Codeigniter Controller "Entry.php" Plunker code is at this link:

https://plnkr.co/edit/MHVVkWwFqEggqSI5b6B2?p=info

Same code is pasted here also: app.module.ts

import { NgModule }            from '@angular/core';
import { BrowserModule }       from '@angular/platform-browser';
import { HttpModule } from "@angular/http";
import { AppComponent }        from './app.component';
import { EntryService }        from './entry.service';

@NgModule({
  imports: [
    BrowserModule,
    HttpModule
  ],
  declarations: [
    AppComponent
  ],
  exports: [ // export for the DemoModule
    AppComponent
  ],
  providers: [ EntryService], 
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app.component.ts

import { Component, OnInit} from '@angular/core';
import { EntryService} from './entry.service';

@Component({  
  selector: 'my-app',
  template: `
      <h3>{{ errorMsg }} </h3>      
      <ul>
          <li *ngFor="let s of scripts">{{ s.price }}</li>
      </ul>
  `,
})

class formEntry{  
  constructor(price: number, qty: number){}    
}
export class AppComponent implements OnInit{

    errorMsg: string;
    data: formEntry;
    constructor(private _entService: EntryService) { }

    ngOnInit()
    {
        console.log('In OnInit: ');        
        this._entService.getData()
            .subscribe(data => this.data = data,
                        resError => this.errorMsg = resError);            
    }
}

entry.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response}  from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/throw';

@Injectable()
export class EntryService { 

     constructor(private _http: Http) { } 

     getData(){

        let myUrl = 'http://localhost/analy/entry/getData';
        return this._http.get(myUrl)
            .map((res: Response ) => res.json())
            .catch(this._errorHandler);
      } 
      _errorHandler(error: Response){
          console.error(error);
          return Observable.throw(error || "Server Error");
      }
}

Entry.php

class Entry extends CI_Controller
{
    function __construct()
    {
        parent::__construct();      

        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Headers: X-Requested-With');
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    }

    function getData(){
        $data = array('price' => 999,
               'qty' => 8);                
        $jdata = json_encode($data);                       
        return ($jdata);
    }
}

I am using webpack 2. The code is not working at plnkr but on my system. But it is working perfectly for mydata.json file but giving error for get request to "entry/getData" (from entry.service.ts). getData is method in Entry.php controller.

What can be the possible cause and what is possible solution..??? Please any one can please help me out to resolve the problem.

like image 218
Ramji Makwana Avatar asked Mar 02 '17 13:03

Ramji Makwana


2 Answers

Just ran into this issue with angular 4 when I upgraded to use the new HttpClient from @angular/common/http

The interesting thing with HttpClient is that it automatically runs .json() on your responses. This causes problems when the api returns back an empty response. You'll then get the Unexpected end of json error. The solution is to set responseType as text:

http.get(url, { responseType: 'text' })
like image 150
seescode Avatar answered Oct 22 '22 03:10

seescode


You are trying to parse a null value as a JSON

return this._http.get(myUrl)
        .map((res: Response ) => res.json())
        .catch(this._errorHandler);

If res is null/undefined/empty string you will get the error. Just check for the value of res before doing res.json() and you won't get the error. To be sure of this make a console.log(res) before trying to parse it.

like image 7
Gianluca Paris Avatar answered Oct 22 '22 03:10

Gianluca Paris