Reputation: 3564
So I'm trying to get JSON data from php file but the console shows me this error:
EXCEPTION: Unexpected token < in JSON
I just sent a simple json array via php like this:
<?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));
This is the location of my php file:
And finaly this is my service class:
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;
});
}
}
I really googled a lot for this problem and tried a lot of solutions but still getting the same error !
Upvotes: 4
Views: 744
Reputation: 73367
Your WAMP is hosted under a different domain, so it won't work if you try and add the PHP files in your Angular 2 project.
The fast and easy solution is...
You would actually keep the PHP files under that domain (localhost in your case) and make http-requests to those files like: http://localhost/file.php
. This is of course a cross-domain request, so you need to add the appropriate headers in the PHP-file. From my experience the following has been working:
header('Access-Control-Allow-Origin: *');
Of course cross-domain requests are not optimal here, but since this issue is present in development mode, I have not found it to be a problem.
One additional problem that might occur here as well, is that you need to enable CORS in your browser. For that there is a great extension for chrome here.
Upvotes: 1
Reputation: 2905
You cant serve php directly you need apache server to execute (use xampp) and the src folder is not a public folder you can store mock data to assets folder.
Upvotes: 0