简体   繁体   English

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

[英]Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)

I know this topic already exist on this platform. 我知道这个话题已经存在于这个平台上。 I have searched through online but I didn't get the rightful answer pertaining to my problem. 我已经在线搜索过,但是没有得到与我的问题有关的正确答案。

I created a login page which needs to access API but every time I clicked on the Login button the error comes out. 我创建了一个需要访问API的登录页面,但是每次我单击“登录”按钮时,都会出现错误。

I have tried different ways but still couldn't figure it out. 我尝试了不同的方法,但仍然无法弄清楚。

Below is my source codes: 下面是我的源代码:

Login.html 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 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 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 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);

?> 

Could someone please point me to the right direction. 有人可以指出我正确的方向。

It's because your API doesn't return valid JSON response. 这是因为您的API无法返回有效的JSON响应。 You should catch these errors: 您应该捕获以下错误:

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');
             });
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获到的SyntaxError:JSON中的意外令牌&lt;在JSON.parse位置0处( <anonymous> ) - Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) SyntaxError:JSON中的意外令牌&lt;位于JSON.parse(位置0) <anonymous> )-AngularJS - SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) - AngularJS Uncaught SyntaxError: Unexpected token &lt; in JSON at position 0 at JSON.parse (<anonymous> ) 在 XMLHttpRequest。<anonymous></anonymous></anonymous> - Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous> Uncaught SyntaxError: Unexpected token &lt; in JSON at position 0 : at JSON.parse (<anonymous> ) 在对象。<anonymous> - Uncaught SyntaxError: Unexpected token < in JSON at position 0 : at JSON.parse (<anonymous>) at Object.<anonymous> 显示SyntaxError的json响应:意外令牌[JSON中JSON.parse( <anonymous> ) - json response showing SyntaxError: Unexpected token [ in JSON at position 23 at JSON.parse (<anonymous>) jQuery.Deferred exception: Unexpected token &lt; in JSON at position 0 SyntaxError: Unexpected token &lt; in JSON at position 0 at JSON.parse (<anonymous> )</anonymous> - jQuery.Deferred exception: Unexpected token < in JSON at position 0 SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) 我正在使用Ionic并收到错误消息:SyntaxError:JSON中的意外标记&lt;在JSON.parse位置0处( <anonymous> ) - I am using ionic and getting an error: SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous> ) - VM299:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 未捕获到的SyntaxError:JSON中的意外令牌&lt;在JSON.parse的位置2 <anonymous> )在对象上。 <anonymous> (userhistory.js:23) - Uncaught SyntaxError: Unexpected token < in JSON at position 2 at JSON.parse (<anonymous>) at Object.<anonymous> (userhistory.js:23) Ionic + PHP:意外的令牌&lt;JSON中的JSON.parse位置0 - Ionic + PHP: Unexpected token < in JSON at position 0 at JSON.parse
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM