Im writing an Angular2 application with php backend. When I make a request to the server from the angular application, it sends me this error message in the browser console.
Unexpected token < in JSON at position 0
I have read a question regarding this problem. They say the problem is with the response type of the http
response. They say that, response type should be json
. But response type is text/html
in my application.
This is the service.ts file related to my problem user.service.ts
import { Injectable } from '@angular/core';
import {User} from '../models/user';
import {Http} from '@angular/http';
@Injectable()
export class UserService {
private currentUser: User;
constructor(private http: Http) {
this.currentUser = new User(null, null, null, false);
}
getCurrentUser() {
return this.currentUser;
}
logIn(username, password) {
let curUser = new User(username, password, null, false);
this.http.post('http://localhost/back_End/controllers/user.php/', {'username': username , 'password': password})
.map(res => res.json())
.subscribe(
users => {
curUser = users[0];
console.log(curUser);
}
);
console.log(curUser);
}
Problem is related to the logIn
method.
This is the corresponding php file user.php
<?php
$data = json_decode(file_get_contents("php://input"));
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$server_ame = "localhost";
$username = "root";
$password = "";
$dbname = "yathra";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "select * from user where username='$data->username' and password='$data->password'";
$result = $conn->query($sql);
if($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
}else {
echo "0 results";
}
echo json_encode($data);
$conn->close();
?>
I'm new to Angular2. Can someone give me a solution for this?
You may Try For this:
The problem was here,because of you use json() instead of json
json - always return text(that may be HTML,PHP,XHTML etc).
this.http.post('http://localhost/back_End/controllers/user.php/', {'username': username , 'password': password}) .map(res => res.json) // SEE HERE .subscribe( users => { curUser = users[0]; console.log(curUser); } );