Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48980

Can't pass bearer token in HTTP header, blank constant?

$
0
0

I have been playing with OAuth and connecting to an API I have built. I can test it and it works just fine in both Postman and when specifying my key as a string but I can’t get the bearer token to be sent with the HTTP GET request. I’m stumped.

My code is as follows:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@capacitor/storage';
import { AlertController } from '@ionic/angular';
import { tap } from 'rxjs/operators';
import { EnvService } from './env.service';
@Injectable({
  providedIn: 'root'
})
export class DeploymentService {

  token = '';

  constructor(
    private http: HttpClient,
    private env: EnvService,
    private alertCtrl: AlertController
  ) { }

  async test() {
    const { value } = await Storage.get({ key: 'token-key' });
    this.token = value;
    const alert = await this.alertCtrl.create({
      header: 'BEARER',
      message: this.token,
      buttons: ['OK']
    });
    alert.present();
  };

  getDeployments() {

    const headers = { 'Authorization': `Bearer ${this.token}` }

    return this.http
      .get(this.env.API_URL + '/api/deployments', { headers: headers })
      .pipe(tap(resData => {
        console.log(resData);
      }))
  }
}

As you can see, I have included an alert controller, more so I can test the token constant was actually being modified. But whenever I try to use the same logic to pass token in to the header, I get the 401 because the constant is blank.

It does work if I manually include the token as the value to the constant but doesn’t work any other way.

Where am I going wrong?

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48980

Trending Articles