Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.
Wall Script
Wall Script
Thursday, June 22, 2017

Ionic 3 and Angular 4: PHP Restful API User Authentication for Login and Signup.

Here is the continued article on my previous post for creating a welcome page with login and logout. Today’s post explains how to implement login authentication system for your AngularJS applications. It will show you how to log in with a user and store the user session, so it deals with token based authentication. Since we are using token based authentication, it protects if any unauthorized request is made and notices for a new login if required. This makes your application’s authentication to be more secured compared with any other authentication system. Every user details will be stored in an external database and a PHP based API is used in the backend for handling this authentication. Hope you’ll find it more easily using this as your authentication system in your AngularJS projects. Let’s look into the live demo and follow the below code.

Ionic 3 and Angular 4:Login and Signup with PHP Restful API.


Live Demo


Video Tutorial
Ionic 3 and Angular 4: PHP Token Based Restful API User Authentication Login and Signup.


Database Design
To build the user feed system, you have to create two tables such as Users and Feed. You can check my previous tutorials for creating token-based API system.

Users
User table contains all the users registration details.
CREATE TABLE users(
user_id int AUTO_INCREMENT PRIMARY KEY,
username varchar(50),
password varchar(300),
name varchar(200),
email varchar(300));

Feed
This table contains user daily updates.
CREATE TABLE feed(
feed_id int PRIMARY KEY AUTO_INCREMENT,
feed text,
user_id_fk int
);

Download PHP Restul Project
$git clone https://github.com/srinivastamada/PHP-Slim-Restful.git


Create an Authenstication Service Provider
You have to create an injectable component for API autentication. The following ionic command help you to create files automatically.
$ionic g provider authService

app.module.ts
Now go to src/app/app.module.ts and import authService provider and HttpModule.
Now got src/app/app.module.ts and import Welcome, Login and Signup pages.
import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { MyApp } from './app.component';
import { AuthService } from '../providers/auth-service';
import { Welcome } from '../pages/welcome/welcome';
import { Login } from '../pages/login/login';
import { Signup } from '../pages/signup/signup';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  imports: [
    BrowserModule, HttpModule
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage,
    ContactPage,
    HomePage,
    Welcome,
    Login,
    Signup,
    TabsPage
  ],
  providers: [
    StatusBar,
    SplashScreen, AuthService,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

authService.ts
Include post data function for HTTP post access. You will understand more in the youtube video.
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = 'http://yourdomain.com/PHP-Slim-Restful/api/';

@Injectable()
export class AuthService {

  constructor(public http : Http) {
    console.log('Hello AuthService Provider');
  }

  postData(credentials, type) {
    return new Promise((resolve, reject) => {
      let headers = new Headers();

      this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
        .subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(err);
        });
    });

  }

}

signup.ts
Here you have to import AuthService provider and implement with user signup data. Once the API call is succesful, the user data storing into application local storage with accessing data key call userData.
import { Component } from '@angular/core';
import {  NavController} from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { AuthService } from '../../providers/auth-service';

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class SignupPage {
  responseData : any;
  userData = {"username": "","password": "", "name": "","email": ""};

  constructor(public navCtrl: NavController, public authService:AuthService ) {
  }

  signup(){
     this.authService.postData(this.userData,'signup').then((result) => {
      this.responseData = result;
      if(this.responseData.userData){
      console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
      }
      else{ console.log("User already exists"); }
    }, (err) => {
      // Error log
    });

  }

  login(){
    //Login page link
    this.navCtrl.push(LoginPage);
  }
}

signup.html
Bind the userDetails object with form inputs.
<ion-content padding class="appBackground">
  <ion-card>
    <ion-card-header>
      Registration
    </ion-card-header>
    <ion-card-content>
      <ion-list>
        <ion-item>
          <ion-label stacked>Name</ion-label>
          <ion-input type="text" [(ngModel)]="userData.name"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Email</ion-label>
          <ion-input type="text" [(ngModel)]="userData.email"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Username</ion-label>
          <ion-input type="text" [(ngModel)]="userData.username"></ion-input>
        </ion-item>

        <ion-item>
          <ion-label stacked>Password</ion-label>
          <ion-input type="password" [(ngModel)]="userData.password"></ion-input>
        </ion-item>

        <button ion-button full color="success" (click)="signup()">Sign up</button>
        <a href="#" (click)="login()">Login Page</a>
      </ion-list>
    </ion-card-content>
  </ion-card>
</ion-content>

login.ts
You have to follow the same like signup module.

home.ts
Reading the application local storage data and binding with userDetails. Logout function is clearing the local storage data and redirecting to the welcome page with time deplay option.
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})

export class HomePage {

  userDetails : any;
  responseData: any;

  userPostData = {"user_id":"","token":""};

  constructor(public navCtrl: NavController, public authService:AuthService) {
  const data = JSON.parse(localStorage.getItem('userData'));
  this.userDetails = data.userData;

  this.userPostData.user_idthis.userDetails.user_id;
  this.userPostData.tokenthis.userDetails.token;

}

backToWelcome(){
   const root = this.app.getRootNav();
   root.popToRoot();
}

logout(){
     localStorage.clear();
     setTimeout(() => this.backToWelcome(), 1000);
}

}

home.html
Binding the local storage data with HTML template.
<ion-header>
  <ion-navbar>
    <img ion-right src="assets/imgs/bananalogo.png" class="navbarLogo" />
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to {{userDetails.name}}</h2>
  <h3>Email: {{userDetails.email}}</h3>
  <button ion-button color="primary" (click)="logout()">Logout</button>
</ion-content>

Build iOS App
Following commands for executing Xcode build, watch the video tutorial you will understand more.
$ cordova platform add ios
$ ionic build ios

Build Android App
Open Android build using Android SDK>
cordova platform add android
ionic build android

Previous Video Tutorial
Ionic 3 and Angular 4 Create a Welcome Page with Login and Logout.



web notification

111 comments:

  1. could you just make upload Ionic 3 and Angular 4 json parsing Example and Push Notification pls.
    Thanks
    -Sapan

    ReplyDelete
  2. This is video too much helpfull and work for me
    Thanks
    -sapan

    ReplyDelete
  3. Thanks man so helpfull keep i up

    ReplyDelete
  4. your tutorials helping to me lot, thanks

    ReplyDelete
  5. why there is not error message if i use random account

    ReplyDelete
  6. Error: this.userDetails is undefined

    ReplyDelete
    Replies
    1. Clear your browser local storage. Go to developer tools -> application -> Clear Site Data

      Delete
    2. Thank you so much. Ok After log in, user can insert some details to other table How can we do ... can you please help me ? like want to insert feed data from ionic.

      Delete
    3. Hi Srinivas, some how I've done inserting data from ionic.
      One thing I want to know how to display toast msg when same user signup like "user already existed" ?

      Delete
  7. {"error":{"text":"Enter valid data"}}

    ReplyDelete
  8. am also getting this error {"error":{"text":"Enter valid data"} please help.!

    ReplyDelete
  9. The video is very helpful. Thanks for the share

    ReplyDelete
  10. Help!!
    XMLHttpRequest cannot load http://192.168.1.10/slimrest/index.php/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

    ReplyDelete
    Replies
    1. I was error too, u did edit it ? Can u help me?

      Delete

    2. if (isset($_SERVER['HTTP_ORIGIN'])) {
      header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
      header('Access-Control-Allow-Credentials: true');
      header('Access-Control-Max-Age: 86400'); // cache for 1 day
      }

      // Access-Control headers are received during OPTIONS requests
      if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
      header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

      if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
      header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

      exit(0);

      Add these lines to the php file on top

      Delete
  11. ERROR DOMException [NetworkError: "A network error occurred."
    code: 19
    nsresult: 0x80530013
    location: http://localhost:8100/build/polyfills.js:3]

    ReplyDelete
  12. Have an example of registration With SMS code using Restfull API??

    ReplyDelete
  13. i got this error:

    Property 'app' does not exist on type 'HomePage'

    please help

    ReplyDelete
    Replies
    1. import { App, NavController } from 'ionic-angular';

      constructor(public navCtrl: NavController, public appCtrl: App, public authService:AuthService)

      const root = this.appCtrl.getRootNav();

      Delete
  14. {error: {…}}error: text: "Enter valid data" iam getting error while signup

    ReplyDelete
    Replies
    1. Do you fix it? i am getting the same error!!

      Delete
    2. Go to Your index.php on the signup function..look for where it says "echo " and delete it..also just 2-3 lines below it says "echo here"..delete that too..your erroris fixed

      Delete
  15. hi, when i'm submitting the form using yours api module, then we get an error of "XMLHttpRequest cannot load http://mywebsite.com/Home/Login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access."

    my api is build in .net , so can you help me, coz im new to ionic

    ReplyDelete
    Replies
    1. hi
      if you install this plugin, your problem solved
      https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

      Delete
  16. hi , im new to ionic so i'll see your video, then apply same on my project, but when we run the postData function it returns "XMLHttpRequest cannot load http://mywebsite.com/Home/Login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access."

    and this API is made on .NET

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Work like Charm, i have learnt a lot from it greatly, thanks

    ReplyDelete
  19. never mind my previous comment requesting help on alertbox. i got it working :D

    ReplyDelete
  20. hello sir. please i am getting this error upon signup. my tabs page is not showing and my signup datas are storing into my database.

    Runtime Error
    Unexpected token < in JSON at position 0
    Stack
    SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse ()
    at Response.Body.json (http://localhost:8100/build/vendor.js:66426:25)
    at SafeSubscriber._next (http://localhost:8100/build/main.js:324:29)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:36172:16)
    at SafeSubscriber.next (http://localhost:8100/build/vendor.js:36119:22)
    at Subscriber._next (http://localhost:8100/build/vendor.js:36059:26)
    at Subscriber.next (http://localhost:8100/build/vendor.js:36023:18)
    at XMLHttpRequest.onLoad (http://localhost:8100/build/vendor.js:66855:38)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:9967)
    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:4499:37)

    ReplyDelete
    Replies
    1. Did you solve this problem? Got the same here...

      Delete
    2. Do you have any idea? I got the same issue.
      Pls help.

      Delete
    3. im having this problem too

      Delete
    4. please help with this problem. i'm having it too

      Delete
  21. What happens when you start the session in two devices?

    ReplyDelete
  22. Hi Srinivas i have two errors,
    one is when i try to register a user and show me a error:
    "{error: {…}}error: text: "Enter valid data"

    and two, i register a user in mysql and trying to login show me this error

    "Bad request wrong username and password"

    can you help me please? i'm trying to understand web services
    Greetings

    ReplyDelete
    Replies
    1. Hi, Look like you haven't completed the registration process. Give valid information and try, you will get inserted user information data set.

      Delete
  23. SyntaxError: Unexpected end of JSON input

    ReplyDelete
  24. How to get details of user after login using token value.... thanks....

    ReplyDelete
    Replies
    1. Take a look at this link https://www.9lessons.info/2017/07/ionic-angular-JSON-parsing-json-APIs.html

      Delete
  25. Hai sir, I get error {"error":{"text":"Enter valid data"}} while i try signup function . please help !

    ReplyDelete
  26. Hi, I am new. Where do I physically store the api files?

    ReplyDelete
  27. Hi! Where do I store the api files?

    ReplyDelete
    Replies
    1. Install XAMPP(Apache PHP MySQL) server and copy api file in htdocs folder.

      Delete
  28. Hi sir,
    This code error after i m update cordove to version 7.1.0 :

    Typescript Error
    Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. Property 'keys' is missing in type 'Headers'.
    D:/ionic/ionic-welcome/src/providers/auth-service/auth-service.ts
    this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
    .subscribe(res => {

    ReplyDelete
  29. Hi Sir,
    Error when build or run on android device

    ReplyDelete
  30. hi sir,
    i like yours lessons. thanks so much.
    My question is; what is your text editor software you are using to open projet?
    Thanks so much

    ReplyDelete
  31. when i apply setTimeout function... no action performed :(

    ReplyDelete
  32. when i use setTimeout function .. no action perform :(

    ReplyDelete
  33. If any tutorial available Ionic with C#.net web api code? pls help?

    ReplyDelete
  34. I resolved the error " Enter Valid Data". Basically, we have data validity check in our API. So PREG_MATCH does this logic. If you provide valid credentials while you enter the details for Sign-up. it works fine. For example, make sure you have alphanumeric value for password & right input for email & so on. It should work fine!..

    Thank you Srinivas!, very nice tutorial

    ReplyDelete
  35. my first ionic app create using this post...
    very helpful post..
    thanks very much...

    ReplyDelete
  36. Hi Srinivas,

    The error is displayed when calling singup in app

    ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'user_id' of undefined
    TypeError: Cannot read property 'user_id' of undefined
    at new HomePage (home.ts:21)

    What´s wrong?

    ReplyDelete
    Replies
    1. Modify following code.

      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);

      to

      if(this.responseData.userData)
      {
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      this.navCtrl.push(TabsPage);
      }

      Delete
    2. console.log(this.responseData.userData) = undefinded ?? why? pls help!

      Delete
    3. Console.log(this.resposeData.userData)is giving undefined result for me too. Anyone has solved the issue...

      Delete
  37. nice post bro... i really like that... you helping me to learn about ionic...

    ReplyDelete
  38. Hi Srinivas,

    at first I want to thank you for this great tuturial.

    I have problem when I try to Signup to my Database. The user is created in my Database, but I've get this Error in my Browser:

    ERROR
    SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 2 of the JSON data
    Stack trace:
    Body.prototype.json@http://localhost:8100/build/vendor.js:66955:20
    [155]/AuthServiceProvider.prototype.postData/</<@http://localhost:8100/build/main.js:143:25
    SafeSubscriber.prototype.__tryOrUnsub@http://localhost:8100/build/vendor.js:33683:13
    SafeSubscriber.prototype.next@http://localhost:8100/build/vendor.js:33630:17
    Subscriber.prototype._next@http://localhost:8100/build/vendor.js:33570:9
    Subscriber.prototype.next@http://localhost:8100/build/vendor.js:33534:13
    onLoad@http://localhost:8100/build/vendor.js:67448:21
    F</l</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:15649
    onInvokeTask@http://localhost:8100/build/vendor.js:4973:24
    F</l</t.prototype.invokeTask@http://localhost:8100/build/polyfills.js:3:15562
    F</c</r.prototype.runTask@http://localhost:8100/build/polyfills.js:3:10815
    F</h</e.invokeTask@http://localhost:8100/build/polyfills.js:3:16787
    p@http://localhost:8100/build/polyfills.js:2:27646
    v@http://localhost:8100/build/polyfills.js:2:27893
    core.js:1350

    defaultErrorLogger
    core.js:1350
    ErrorHandler.prototype.handleError
    core.js:1411
    IonicErrorHandler.prototype.handleError
    ionic-error-handler.js:61
    next
    core.js:5376:134
    EventEmitter.prototype.subscribe/schedulerFn<
    core.js:4223:34
    SafeSubscriber.prototype.__tryOrUnsub
    Subscriber.js:238
    SafeSubscriber.prototype.next
    Subscriber.js:185
    Subscriber.prototype._next
    Subscriber.js:125
    Subscriber.prototype.next
    Subscriber.js:89
    Subject.prototype.next
    Subject.js:55
    EventEmitter.prototype.emit
    core.js:4203:22
    onHandleError/<
    core.js:4651:48
    F</l</t.prototype.invoke
    http://localhost:8100/build/polyfills.js:3:14974
    F</c</r.prototype.run
    http://localhost:8100/build/polyfills.js:3:10124
    NgZone.prototype.runOutsideAngular
    core.js:4577:47
    onHandleError
    core.js:4651
    F</l</t.prototype.handleError
    http://localhost:8100/build/polyfills.js:3:15054
    F</c</r.prototype.runTask
    http://localhost:8100/build/polyfills.js:3:10869
    F</h</e.invokeTask
    http://localhost:8100/build/polyfills.js:3:16787
    p
    http://localhost:8100/build/polyfills.js:2:27646
    v
    http://localhost:8100/build/polyfills.js:2:27893

    I can't finde the mistake. Can you help me with this?

    Thank you in advance


    ReplyDelete
    Replies
    1. Check your signup resful api with chrome POSTman

      Delete
    2. Thank you for your reply. With Postman I get no error. In Chrome I get this error:

      ERROR SyntaxError: Unexpected token < in JSON at position 1
      at JSON.parse ()
      at Response.Body.json (http.js:1063)
      at SafeSubscriber._next (auth-service.ts:21)
      at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
      at SafeSubscriber.next (Subscriber.js:185)
      at Subscriber._next (Subscriber.js:125)
      at Subscriber.next (Subscriber.js:89)
      at XMLHttpRequest.onLoad (http.js:1556)
      at t.invokeTask (polyfills.js:3)
      at Object.onInvokeTask (core.js:4620)

      Delete
    3. Please take the update, fixed the signup part.

      $git pull

      Delete
    4. help sir..

      ERROR SyntaxError: Unexpected token < in JSON at position 1
      at JSON.parse ()
      at Response.Body.json (http.js:1063)
      at SafeSubscriber._next (auth-service.ts:28)
      at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
      at SafeSubscriber.next (Subscriber.js:185)
      at Subscriber._next (Subscriber.js:125)
      at Subscriber.next (Subscriber.js:89)
      at XMLHttpRequest.onLoad (http.js:1556)
      at t.invokeTask (polyfills.js:3)
      at Object.onInvokeTask (core.js:4620)

      Delete
    5. Hello I have the same error how to do? Do you have a last update on which file?

      Delete
  39. Hi Srinivas,
    I am new to IONIC
    I am getting this error when trying to signup.
    polyfills.js:3 POST http://localhost:8100/undefinedsignup 404 (Not Found)
    The data is inserting in postman. but not from app.
    Please help
    Thanks in advance

    ReplyDelete
  40. First i have to thanks for this great article....only i have not been able to get it to work..i get the following error.

    Can't resolve all parameters for HomePage: ([object Object], ?).

    pls help

    ReplyDelete
  41. {"error":{"text":SQLSTATE[HY000] [1049] Unknown database 'banan'}}
    i am getting this error in postman

    ReplyDelete
  42. Please help!
    I'm getting {"error":{"text":"Enter valid data"}} when i try to test the signup endpoint from fiddler

    This is how my request body looks:
    {
    username: "Tamada",
    password: "ade123",
    email: "[email protected]",
    name: "Srinivas Tamada"
    }

    ReplyDelete
    Replies
    1. I also got tis problem. r u fix it already? can help me?

      Delete
  43. I taken the last version but In Chrome I get this error anyways:

    ERROR SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse ()
    at Response.Body.json (http.js:1063)
    at SafeSubscriber._next (auth-service.ts:21)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.js:1556)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4620)

    And when i try to login i'm stucked at "Please Wait" pop-up

    Help me, thanks

    ReplyDelete
  44. I have error in auth-service this.http.post(apiurl+type, JSON.stringify(credentials), {headers:headers}).subscribe(res =>{
    resolve(res.json());

    ReplyDelete
  45. Hi Srinivas,
    This code error after i m update cordove to version 7.1.0 :

    Typescript Error
    Argument of type '{ headers: Headers; }' is not assignable to parameter of type 'RequestOptionsArgs'. Types of property 'headers' are incompatible. Type 'Headers' is not assignable to type 'Headers'. Two different types with this name exist, but they are unrelated. Property 'keys' is missing in type 'Headers'.
    D:/ionic/ionic-welcome/src/providers/auth-service/auth-service.ts
    this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
    .subscribe(res => {

    ReplyDelete
    Replies
    1. Im using cordova v8.0.0 and Im getting the same error, can you please tell me how did you solve it. Thanks in advance

      Delete
  46. 404 Page Not Found
    when trying to access signup and so as other functions. Please help. Thanks

    ReplyDelete
  47. Please give me solution for this error
    When I submit data at time I get error invalid character and data not inserted into database

    ReplyDelete
    Replies
    1. how to get git code update, please give full command line.

      Delete
  48. This is video too much help-full and work for me
    Thanks bro.

    ReplyDelete
  49. tengo este error core.js:1350 ERROR SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse ()
    at Response.Body.json (http.js:1063)
    at SafeSubscriber._next (auth-service.ts:20)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.js:1556)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4620)

    ReplyDelete
  50. when click submit button i got

    TypeError: res.json is not a function
    at SafeSubscriber._next (http://localhost:8100/build/main.js:519:29)
    at SafeSubscriber.__tryOrUnsub .......

    please help,
    (i'm using ionic 3 angular 5)

    ReplyDelete
    Replies
    1. In HttpClientModule, json is a default option and you do not need to parse the res to json.

      Change "resolve(res.json());" to "resolve(res);" and you are good to go.

      Delete
  51. I having error.I don't know how to solve
    Runtime Error Uncaught (in promise): invalid views to insert
    These error came when i click signup or login buttons

    ReplyDelete
  52. When I Access "localhost/PHP-SLim-Restful/api" It Shows 404 PAge Not Found Error

    How To Solve this?

    ReplyDelete
  53. Hi, I Followed your video tutorials,when users signup,that those datas are stored correctly..but my issue is,when clicking the signup button its not moving to tabs page...but in console there is no issue...have any idea??

    ReplyDelete
  54. hi, i can't acces to this.responseData.userData, i've follow exactly your tuto but i can't find a solution.

    ReplyDelete
  55. Hi my developer tools in google chrome, console log shows "no Access at home.ts line 53", while I have already sign up and the page directed me to welcome page with a please wait and a loading circle in the middle of page that goes on for ever please help how to get rid of this "please wait message" . thanks

    ReplyDelete
  56. hi srinivas, thanks for the tutorials.
    I want to ask something..
    why my signup button is not working, I've done the same thing as you did??

    ReplyDelete
  57. I have this error : Uncaught (in promise): [object Object]

    ReplyDelete
  58. Hii all,
    This errors comes from your api index.php file. Error in signup function.
    Just do 2things then your app running well. Just remove or comment out this 2 line of code.
    1. //echo $email_check.'
    '.$email;
    2. //echo 'here';

    ReplyDelete
  59. Hello M Srinivas, I want you to help me about something, I followed you tutorial and it help me so much.
    Now I want to fetch data from a table and displayed it in a view. How do I proccess?
    Thanks in advance!

    ReplyDelete
  60. Hello there everybody, I get the 404 Page Not Found, no matter what I tr to do...

    ReplyDelete
  61. this is what i get from the browser:

    Object not found!
    The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again.

    If you think this is a server error, please contact the webmaster.

    Error 404
    localhost
    Apache/2.4.23 (Win32) OpenSSL/1.0.2h PHP/5.6.28

    ReplyDelete
  62. Replies
    1. Enable mod_rewrite extension for PHP. This will support .htaccess file for redirections.

      Possible use XAMPP it comes with better settings

      Delete
  63. I managed to signup and the data entered the database but at the app display runtime error "unexpected token S in JSON at position 17"

    ReplyDelete
  64. Hi ,
    after testing code , I have an error with http headers give this message :


    Blocage d’une requête multiorigines (Cross-Origin Request) : la politique « Same Origin » ne permet pas de consulter la ressource distante située sur http://localhost/PHP-Slim-Restful/api/signup. Raison : l’en-tête CORS « Access-Control-Allow-Origin » est manquant.

    how can I solve it please

    ReplyDelete
  65. In my signup.ts file

    responseData : any;
    userData = {
    'customer': {
    "email":"",
    "firstname":"",
    "lastname":"",
    "storeId":1,
    "websiteId":1
    },
    "password":""
    };

    signup() {
    //REST API connection to Magento 2 for Siging up a new customer
    //this.navCtrl.push(HomePage);
    this.authServiceProvider.postData(this.userData, "signup").then((result) => {
    this.responseData = result;
    if(this.responseData.userData){
    console.log(this.responseData);
    localStorage.setItem('userData', JSON.stringify(this.responseData));
    this.navCtrl.setRoot(HomePage);
    } else {
    console.log("User already exists");
    }
    }, (err) => {
    //connection failed error message
    });
    }



    when i do console.log(this.responseData); it shows NULL what am doing wrong ?

    ReplyDelete
  66. Hi Shrinivas, I've copied he same CLI "ionic g provider authService", afetr ionic serve command i'm getting "Error: Cannot find module "../providers/auth-service" ".

    The auth-service.ts code, That i've got ==>

    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';

    /*
    Generated class for the AuthServiceProvider provider.

    See https://angular.io/guide/dependency-injection for more info on providers
    and Angular DI.
    */
    @Injectable()
    export class AuthServiceProvider {

    constructor(public http: HttpClient) {
    console.log('Hello AuthServiceProvider Provider');
    }

    }


    Please help me

    ReplyDelete
  67. How to solve this error

    TypeError: res.json is not a function
    at SafeSubscriber._next (http://localhost:8100/build/main.js:135:29)
    at SafeSubscriber.__tryOrUnsub (http://localhost:8100/build/vendor.js:35277:16)
    at SafeSubscriber.next (http://localhost:8100/build/vendor.js:35224:22)
    at Subscriber._next (http://localhost:8100/build/vendor.js:35164:26)
    at Subscriber.next (http://localhost:8100/build/vendor.js:35128:18)
    at MapSubscriber._next (http://localhost:8100/build/vendor.js:117951:26)
    at MapSubscriber.Subscriber.next (http://localhost:8100/build/vendor.js:35128:18)
    at FilterSubscriber._next (http://localhost:8100/build/vendor.js:119697:30)
    at FilterSubscriber.Subscriber.next (http://localhost:8100/build/vendor.js:35128:18)
    at MergeMapSubscriber.notifyNext (http://localhost:8100/build/vendor.js:62289:30)

    ReplyDelete
  68. Hi Srinivas, when running in Chrome browser and on device i amd getting the following error

    core.js:1350 ERROR SyntaxError: Unexpected token < in JSON at position 1
    at JSON.parse ()
    at Response.Body.json (http.js:1063)
    at SafeSubscriber._next (auth-service.ts:26)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.next (Subscriber.js:185)
    at Subscriber._next (Subscriber.js:125)
    at Subscriber.next (Subscriber.js:89)
    at XMLHttpRequest.onLoad (http.js:1556)
    at t.invokeTask (polyfills.js:3)
    at Object.onInvokeTask (core.js:4620)

    Any ideas ?

    ReplyDelete
  69. i have problem not able to redirect tabpage after successful signin or signup where return status 200.

    this.navCtrl.push(TabsPage);

    Please help

    ReplyDelete
  70. Hi Srinivas, have you considering update the lesson for ionic 4?

    ReplyDelete
  71. Hi Srinivas, have you considering update the lesson for ionic 4?

    ReplyDelete
  72. where is login page html and calling login function to server on ts???

    ReplyDelete

mailxengine Youtueb channel
Make in India
X