【发布时间】:2017-03-06 09:54:45
【问题描述】:
所以我试图从 php 文件中获取 JSON 数据,但控制台显示此错误:
EXCEPTION: Unexpected token < in JSON
我刚刚通过 php 发送了一个简单的 json 数组,如下所示:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
$res = [
array(
'title' => 'First task',
'description' => 'skdfjsdfsdf',
'done' => false,
),
array(
'title' => 'Second task',
'description' => 'skdfjsdfsdf',
'done' => false,
),
array(
'title' => 'Third task',
'description' => 'skdfjsdfsdf',
'done' => false,
)
];
echo json_encode(array('tasks' => $res));
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class TasksDataService {
constructor(private http: Http) {}
getTasks(){
return this.http.get('http://localhost:4200/src/database.php')
.map(res => {
console.log(res.json());//--I get the error in this line
var result = res.json().tasks;
console.log(result);
return result;
});
}
}
我真的为这个问题搜索了很多,并尝试了很多解决方案,但仍然遇到同样的错误!
【问题讨论】:
-
你必须运行 apache、nginx 或其他东西来服务 php。
-
我跑了!
-
我也试过这个命令 "php -S localhost:4200" 但是 angular 不再起作用了
-
是的,我就是这个意思。
-
确实如此。但这只是我在开发过程中使用的,因为在我看来这并不重要,因为它只是开发。准备部署时,您只需构建 Angular 2 项目并将 dist 文件夹的内容扔到您的 apache 服务器上,因此不再有问题 :)