所以我试图从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',array( 'title' => 'Third task',) ]; 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; }); } }
解决方法
您的WAMP托管在不同的域下,因此如果您尝试在Angular 2项目中添加PHP文件,它将无法运行.
您实际上将PHP文件保留在该域下(在您的情况下为localhost)并对这些文件发出http请求,例如:http://localhost/file.PHP.这当然是跨域请求,因此您需要在PHP文件中添加适当的标头.根据我的经验,以下一直在发挥作用:
header('Access-Control-Allow-Origin: *');
当然,跨域请求在这里并不是最佳的,但由于这个问题在开发模式中存在,我还没有发现它是一个问题.
此处可能出现的另一个问题是,您需要在浏览器中启用CORS.为此,chrome here有一个很好的扩展.