Ionic 3 token authentication

Hi everyone. I have some troubles with this code:


import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';

export class UserData {

    public events: Events,
    public storage: Storage,
    public http: Http
  ) { }

  login(username: string, password: string): void {

    var headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded' );
    let options = new RequestOptions({ headers: headers });"http://localhost:2444/api/token", 'username=TEST&password=TEST123', options)
        data => { console.log('yes') },
        error => { console.log('no') }



import { HttpModule } from '@angular/http';

  declarations: [
  imports: [

Everything works fine with POSTMAN:

My code reach always error, printing ‘no’. Why?
Help me please :slight_smile:

Hi, @Pasto92
Try like below code :

let url = this.hostname + endPoint; //your API
    let headers = new Headers();
    headers.append('Access-Control-Allow-Origin' , '*');
    headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
      let options = new RequestOptions({ headers:headers});
   let data= {username:'TEST',password:'TEST123'}
    return new Promise((resolve,reject)=>{"http://localhost:2444/api/token",JSON.stringify(data), options).subscribe(res => {
        }, (err) => {

also, use Cors addon in your browser

Thank you but I don’t understand why my code works well (see image) but after the function subscribe it always goes in error.

hello @Pasto92
can you provide me a screenshot of error ?

If suppose it is CORS issue you have to configure with server side as well…
google respective backend CORS server side handling you are using


Same thing with specific IP instead of ‘localhost’

Thank you, it was CORS. I installed an add-in for chrome and now everything works fine.

Another thing… Why it doesn’t work on my smartphone (with devapp) ?

the server which one you are using for API have to configure with respect to CORS.
Just google how to deal with CORS your server side language

I solved