Ionic 3 token authentication

Hi everyone. I have some troubles with this code:

user-data.ts

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


@Injectable()
export class UserData {

  constructor(
    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 });

    this.http.post("http://localhost:2444/api/token", 'username=TEST&password=TEST123', options)
      .subscribe(
        data => { console.log('yes') },
        error => { console.log('no') }
      );
  };

}

app.module.ts

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

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    HttpModule,
    ...
  ],

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');
    headers.append('Accept','application/json');
    headers.append('content-type','application/json');
      let options = new RequestOptions({ headers:headers});
   let data= {username:'TEST',password:'TEST123'}
    return new Promise((resolve,reject)=>{
       this.http.post("http://localhost:2444/api/token",JSON.stringify(data), options).subscribe(res => {
          resolve(res.json());
        }, (err) => {
          reject(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.
image

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

image

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