【问题标题】:Unexpected end of JSON input in Http get request from Angular 2 to Codeigniter从 Angular 2 到 Codeigniter 的 Http 请求中 JSON 输入意外结束
【发布时间】:2017-03-02 13:12:33
【问题描述】:

Angular 2 与 Codeigniter Hello World 程序完美运行。但 从 Angular 2 向 Codeigniter 控制器“Entry.php”发送 Http 获取请求时出现错误“JSON 输入意外结束” Plunker 代码在此链接:

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

这里也粘贴了相同的代码: 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);
    }
}

我正在使用 webpack 2。代码在 plnkr 上不起作用,但在我的系统上。但它对 mydata.json 文件非常有效,但对“entry/getData”(来自 entry.service.ts)的获取请求给出了错误。 getData 是 Entry.php 控制器中的方法。

可能的原因和可能的解决方案是什么..??? 请任何人都可以请帮助我解决问题。

【问题讨论】:

  • 您是否检查过您的浏览器网络标签,您实际收到的是什么?

标签: json angular get codeigniter-3


【解决方案1】:

当我升级到使用来自 @angular/common/http 的新 HttpClient 时,我刚刚遇到了 angular 4 的这个问题

HttpClient 的有趣之处在于它会自动对您的响应运行 .json()。当 api 返回一个空响应时,这会导致问题。 然后你会得到 Unexpected end of json 错误。解决方法是将responseType设置为文本:

http.get(url, { responseType: 'text' })

【讨论】:

  • 谢谢。我所做的是拦截器,在其中我使用responseType: 'text' 转换请求,然后处理响应并使用try catch 手动解析它,这样我就不会在状态码为200 的空响应上收到响应错误。
  • 在我的最新项目中,我将状态码切换为 204(无内容),而不是拦截器上不运行 .json() 的 try catch 路由。因为实际上没有内容必须是他们实施的地方。但不确定哪个是真正正确的实现,有些人可能无法返回并更改所有状态代码。
  • @HristoEnev,您介意分享您提出的解决方案吗?
  • @EugeneKulabuhov 我用我的拦截器添加了一个要点here
【解决方案2】:

您正在尝试将空值解析为 JSON

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

如果 res 是 null/undefined/empty string 你会得到错误。只需在执行res.json() 之前检查res 的值,您就不会收到错误消息。为确保这一点,请在尝试解析之前创建 console.log(res)

【讨论】:

    猜你喜欢
    • 2017-10-02
    • 2016-12-17
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 2019-07-19
    • 2015-08-05
    相关资源
    最近更新 更多