ionic 2 how to add Authorization in header

2

I've been trying for days and I can not get the following method in ionic 2 .

getMy() {
    return this.http.get("users/my", this.setAuthorization(this.headers))
                    .toPromise()
                    .then(res => res.json())
                    .catch(this.handleError);
}

protected setAuthorization(headers) {
    headers.append("Authorization", "Bearer " + localStorage.getItem("token"));
    return {headers: headers};
}

In my request authorization is simply not being sent:

Edit1DamonDudekdecidedtodootherwiseasIamwiththeionic2versionthatusetheangle4.1.3,iedoesnothavetheinterceptorsIhaveyetimplementedmyownfornowandthisisso

import{Injectable}from'@angular/core';import{Http,ConnectionBackend,Headers,RequestOptions,Request,RequestOptionsArgs}from'@angular/http';@Injectable()exportclassBaseProviderextendsHttp{privateheaders:Headers=newHeaders();privateurlApi:string="*********";

  constructor(backend?: ConnectionBackend, defaultOptions?: RequestOptions) 
  {
    super(backend, defaultOptions);
    this.headers.append("Content-Type", "application/x-www-form-urlencoded; 
    charset=UTF-8");
  }

  request(request: Request, options?: RequestOptionsArgs) {
   if(localStorage.hasOwnProperty("token")) {
     this.headers.append("Authorization", "Bearer " + 
     localStorage.getItem("token"));
   }
   request.url = this.urlApi + request.url;
   request.headers = this.headers;
   return super.request(request, options);
   }
}

Notice how my request was in the chrome log

XMLHttpRequest cannot load *********. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

I just noticed something when I do the request in postman as OPTIONS does not return anything to me anymore as GET returns something to me, I think the problem is that angular is forcing my request to be OPTIONS. Is anyone able to help me?

    
asked by anonymous 21.08.2017 / 20:18

1 answer

0

Do as follows. Set your header before your request:

let headers = new Headers();
headers.append('Authorization', 'Bearer token');

Make the call by passing the header as the object, just like you did:

{ headers: headers }

This works, that's how I use my requests in angular2.

Below is an excerpt of a complete call that I use as a reference.

getCard(idBeneficiario) {
    return new Promise((resolve, reject) => {
        this.storage.get('token').then((value) => {

            let headers = new Headers();
            headers.append('Authorization', value);

            this.http.get(AppConfig.apiEndpoint + '/DadosAdicionais?idBeneficiario=' + idBeneficiario, { headers: headers })
                .subscribe(res => {

                    let data = res.json();

                    resolve(data);
                }, (err) => {
                    reject(err);
                });
        });

    });
}

Remembering: You need to make the imports and define in your constructor as below:

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

constructor(public http: Http) { }
    
21.08.2017 / 20:25