意外的令牌&lt;在JSON位于JSON.parse的位置0(<anonymous>)

时间:2018-03-23 22:06:09

标签: php angular ionic2

我知道此平台上已存在此主题。我在网上搜索过但我没有得到与我的问题有关的正确答案。

我创建了一个需要访问API的登录页面,但每次点击“登录”按钮时都会出现错误。

我尝试了不同的方法,但仍然无法弄明白。

以下是我的源代码:

的login.html

<ion-content  class="login-content" padding>
  <ion-row class="logo-row">
    <ion-col></ion-col>
    <ion-col >
      <img src="../assets/imgs/logo.png" class="img-responsive " id="img2">
    </ion-col>
    <ion-col></ion-col>
  </ion-row>
  <form (submit)="doLogin()">
    <ion-item>

      <ion-input [(ngModel)]="credentials.email" name="email" type="text" placeholder="Email Address" ></ion-input>
    </ion-item>
    <ion-item>
       <ion-input [(ngModel)]="credentials.password" name="password" type="password" placeholder="Password"></ion-input>
    </ion-item>
    <button ion-button class="submit-btn" block type="submit">
      Login
    </button>
  </form>

  <button ion-button class="register-btn" block clear (click)="register()">
    Create New Account
  </button>
</ion-content>

AuthServive.ts

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

let apiUrl = 'http://localhost:90/mySchool/api2/get.php?';

@Injectable()
export class AuthService {

  constructor(public http: Http) {}

  login(credentials) {

    let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;
    return this.http.get(urlDest)
              .map( (res:Response) => res.json());


   /* return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        this.http.post(apiUrl+'login', JSON.stringify(credentials), {headers: headers})
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });*/
  }

  register(data) {
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post(apiUrl+'guest/signup', JSON.stringify(data), {headers: headers})
          .subscribe(res => {
            resolve(res.json());
          }, (err) => {
            reject(err);
          });
    });
  }

  logout(){
    return new Promise((resolve, reject) => {
        let headers = new Headers();
        headers.append('X-Auth-Token', localStorage.getItem('token'));

        this.http.post(apiUrl+'logout', {}, {headers: headers})
          .subscribe(res => {
            localStorage.clear();
          }, (err) => {
            reject(err);
          });
    });
  }

}

Login.ts

import { Component } from '@angular/core';
import { NavController, LoadingController, ToastController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
import { TabsPage } from '../tabs/tabs';
import { RegisterPage } from '../register/register';
import { HomePage } from '../home/home';

export class User {
  email: string;
  password: string;
}

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

  credentials: User = {
    email: '',
    password: ''
  }



  items:any;

  loading: any;
  //loginData = { email:'', password:'' };
  //data: any;

  constructor(public navCtrl: NavController, public authService: AuthService, public loadingCtrl: LoadingController, private toastCtrl: ToastController) {}

  doLogin() {
    //this.showLoader();

    this.authService.login(this.credentials)
                    .subscribe(
                        datas => {
                          //this.loading.dismiss();
                              if(datas.result){
                                this.navCtrl.push(HomePage, {
                                      email: datas.data.id
                                  })

                              }else{ 

                              alert("Invalid user or password")


                              }
        });

    /*this.authService.login(this.loginData).then((result) => {
      this.loading.dismiss();
      this.data = result;
      localStorage.setItem('token', this.data.access_token);
      this.navCtrl.setRoot(TabsPage);
    }, (err) => {
      this.loading.dismiss();
      this.presentToast(err);
    });*/
  }

  register() {
    this.navCtrl.push(RegisterPage);
  }

  showLoader(){
    this.loading = this.loadingCtrl.create({
        content: 'Processing...'
    });

    this.loading.present();
  }

  presentToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 3000,
      position: 'bottom',
      dismissOnPageChange: true
    });

    toast.onDidDismiss(() => {
      console.log('Dismissed toast');
    });

    toast.present();
  }

}

get.php

<?php

header('Access-Control-Allow-Origin: *');


   // Set up the PDO parameters
$Mysqli = new mysqli('127.0.0.1', 'root', '', 'cihmeeting');





      $login = addslashes($_GET['email']);
      $Tsenha = addslashes($_GET['password']);
      //$senha= md5($Tsenha);

      $erro = "";
      $erro .= empty($login) ? "Enter your email \n" : "";
      $erro .= empty($senha) ? "Enter your password \n" : "";

      $arr = array();

      if(empty($erro)){
         $query = "SELECT * FROM users WHERE email = '$login' and password = '$Tsenha'";
         $result = $Mysqli->query($query);

         if($result->num_rows > 0){
            //login Logged
            $obj = $result->fetch_object();

            $arr['result'] = true;
            $arr['data']['id']         = $obj->id;
            $arr['data']['zone_code']      = $obj->zone_code;
            $arr['data']['first_name']       = $obj->first_name;
            $arr['data']['email']  = $obj->email;
         }else{
            $arr['result'] = false;
            $arr['msg'] = "Invalid login details";
         }
      }else{
         $arr['result'] = false;
         $arr['msg'] = $erro;
      }

      echo json_encode($arr);

?> 

有人可以指出我正确的方向。

1 个答案:

答案 0 :(得分:0)

这是因为您的API没有返回有效的JSON响应。你应该抓住这些错误:

login(credentials) {
  let urlDest = "http://localhost:90/mySchool/api2/get.php?username=" + credentials.email + "&password=" + credentials.password;

  return this.http.get(urlDest)
             .map( (res:Response) => res.json())
             .catch(error => {
               // handle error here
               console.log('Server error');
             });
}