Ionic 2 how to add Authorization in header

Asked

Viewed 639 times

2

I’ve been trying for days and I can’t with the following method on 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 simply not being sent my token authorisation:

inserir a descrição da imagem aqui

Edit 1 Damon Dudek decided to do otherwise as I am with the Ionic 2 version using angular 4.1.3, IE does not own the interceptors yet implemented my own for now and this so

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

@Injectable()
export class BaseProvider extends Http {

  private headers: Headers = new Headers();
  private urlApi: 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 got in the Chrome log inserir a descrição da imagem aqui

ai a request passes only that as OPTIONS and returns me CORS problem being that it is 100% enabled on my server

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.

only that I realized one thing when I do the request in Postman as OPTIONS does not return me anything already as GET returns me something, I think the problem is in the fact that the angular is forcing my request to be OPTIONS. Someone might be able to help me?

1 answer

0

Here’s what you do. 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, this is how I use my requests at angular2.

Below is an excerpt from 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 set in your constructor as below:

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

constructor(public http: Http) { }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.