Unexpected token < in JSON at position 0. Simple screen login


#1

I’m a beginner on Ionic 2.
And I’m developing a screen of login using MySQL and PHP, in WampServer.
I created this way:

login.html:

<ion-header>
  <ion-navbar>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="dadosLogin" (ngSubmit)="login()">
    <ion-item>
      <ion-label floating>CPF</ion-label>
      <ion-input name="cpf" type="text" formControlName="cpf"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label floating>Senha</ion-label>
      <ion-input name="senha" type="password" formControlName="senha"></ion-input>
    </ion-item>
    <ion-item>
      <button ion-button full block>Entrar</button>
    </ion-item>
</form>
</ion-content>

login.ts:

import { Component, OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';

import { ServiceProvider } from '../../providers/service-provider';
import { FormBuilder, Validators } from '@angular/forms';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})

export class LoginPage implements OnInit {

  dadosLogin: any = {};
  usuarios: any[];

  constructor(public navCtrl: NavController, private formularioBuilder: FormBuilder, private service : ServiceProvider) {

    this.dadosLogin = formularioBuilder.group({
      cpf: ['', Validators.required],
      senha: ['', Validators.required]
    });

  }

  ngOnInit() {
    this.service.getDados().subscribe(
      dado => this.usuarios = dado,
      erro => console.log(erro)
    );
  }

  login() {
    this.service.postDados(this.dadosLogin.value)
    .subscribe(
      dado => console.log(dado.mensagem),
      erro => console.log(erro)
    );
  }

}

service-provider.ts:

import { Injectable } from '@angular/core';//Injecao da denpendencia
import { Http, Headers, Response, ResponseOptions } from '@angular/http';
import 'rxjs/add/operator/map';

import { Observable } from 'rxjs/Observable';

@Injectable()
export class ServiceProvider {

  api: string = 'http://localhost/apiFala/';

  constructor(public http: Http) {
  }

  getDados() {
    return this.http.get(this.api + 'apiAutenticacao.php').map(res => res.json());
  }

  postDados(parametros) {
    let headers = new Headers({ 'Content-Type' : 'application/x-www-form-urlencoded' });
    return this.http.post(this.api + 'apiAutenticacao.php', parametros, {
      headers: headers,
      method: "POST"
    }).map(
      (response: Response) => { return response.json(); }
    );
  }

}

apiAutenticacao.php

<?php

  header("Access-Control-Allow-Origin:http://localhost:8100");
  header("Content-Type: application/x-www-form-urlencoded");
  header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

  //Le o arquivo e o transforma em string ou se tiver vazio retorna false
  $dados = file_get_contents("php://input");
  $objDados = json_decode($dados);

  $cpf = $objDados->cpf;
  $senha = $objDados->senha;

  $cpf = stripslashes($cpf);
  $senha = stripslashes($senha);
  $cpf = trim($cpf);
  $senha = trim($senha);
  $dados;

  $db = new PDO("mysql:host=localhost;dbname=bd_fala", "root", "");

  if($db) {
    $verificarCpf = mysqli_query("SELECT * FROM usuarios WHERE cpf = '$cpf'");
    $verificarSenha = mysqli_query("SELECT * FROM usuarios WHERE senha = '$senha'");

    if ($verificarCpf == true && $verificarSenha == true) {

      $dados = array('mensagem' => "Logado com sucesso");
      echo json_encode($dados);

    } else {
      $dados = array('mensagem' => "Dados de login não conferem.");
      echo json_encode($dados);
    }

  } else {
    $dados = array('mensagem' => "Não foi possível conectar-se ao banco.");
  }

 ?>

When I’m run ‘ionic serve’ the google-chrome console show this:

The first error is ‘login.ts:30’ and when I put data into inputs and submit, the error is ‘login.ts:30’

I’m looking for in forums, but I don’t found something that really helped me and I see many things.
OBS: I do not have fluency in English, sorry for something error. Thanks!


#2

The error suggests that your client is expecting JSON, but your server is returning something that begins with a ‘<’ character (which is likely HTML).