0

I'm using aurelia-http-client and struggling to both use interceptors and set headers for my requests.

What I need to achieve is;

  • Each Interceptor (request, request error, response, and response error) emits an event using aurelia-event-aggregator when it's triggered.
  • A header is added to each request containing information entered on the page

The only way I've got interceptors to correctly publish events is to use aurelia.container in main.js like below;

import {HttpClient} from 'aurelia-http-client';
import {EventAggregator} from 'aurelia-event-aggregator';

export function configure(aurelia) {
  const container = aurelia.container;

  const httpClient = container.get(HttpClient);
  const ea = container.get(EventAggregator);

  httpClient.configure(config => {
    config.withInterceptor({
      request(request) {
        ea.publish('http-request', request);
        return request;
      },
      requestError(error) {
        ea.publish('http-request-error', error);
       throw error;
      },
      response(response) {
        ea.publish('http-response', response);
        return response;
      },
      responseError(error) {
        ea.publish('http-response-error', error);
        throw error;
      }
    });
  });

  aurelia.use
    .standardConfiguration()
    .developmentLogging()
    .singleton(HttpClient, httpClient);


  aurelia.start().then(() => aurelia.setRoot());
}

Because the header for my request must be set after the App has initialised - I can't do it in the configuration above like most tutorials online do.

Instead, it needs to be set as below;

import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
import {EventAggregator} from "aurelia-event-aggregator";

@inject(HttpClient, EventAggregator)
export class Dashboard {

  requestMethod = "GET";

  constructor(HttpClient, EventAggregator) {
    this.http = HttpClient;
    this.ea = EventAggregator;
  }

  triggerGet() {
    // HEADER NEEDS TO BE SET HERE USING THIS.FOO
    this.http.get(this.url).then(response => {
      console.log("GET Response", response);
    });
  }
}

I've tried variations of;

this.http.configure((configure) => {
  if(this.username && this.password) {
    configure.withDefaults({
      headers: {
        'Authorization': 'Basic ' + btoa(this.username + ":" + this.password)
      }
    });
  }
})

But I can't get anything to alter the header where I need to, and maintain the configuration I've set up in main.js

Tom
  • 4,257
  • 6
  • 33
  • 49
  • Can't you just wrap `HttpClient` in your own class that does all of this and then inject that class instead? – Ashley Grant Jul 12 '17 at 16:21
  • The `configure.withDefault` should only be used to set static headers. If your header depends on a variable it should be set in the interceptor. e.g `request(request) { request.headers.append('Authorization', appState.token); return request; }` – Fabio Jul 12 '17 at 16:22

2 Answers2

1

Fabio Luiz in the comments set me on to a working solution. It's not ideal I don't think, but it works.

I've essentially created an AppState class that I use to pass the username/password to the interceptor;

export class AppState { 

  properties = {};

  clear() {
    this.properties = {};
  }

  set(key, value) {
    this.properties[key] = value;
  }

  get(key) {
    if(this.properties[key]) {
      return this.properties[key];
    } else {
      return false;
    }
  }
}

It's pretty rough and ready, but it's only for a test Application so I'm happy with it.

Here's its use;

import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
import {EventAggregator} from "aurelia-event-aggregator";
import {AppState} from "services/appState";

@inject(HttpClient, EventAggregator, AppState)
export class Dashboard {

    constructor(HttpClient, EventAggregator, AppState) {
        this.http = HttpClient;
        this.ea = EventAggregator;
        this.appState = AppState;

        // Create listeners
    }

    run() {
        if(this.username && this.password) {
            this.appState.set('authenticate', true);
            this.appState.set('username', this.username);
            this.appState.set('password', this.password);
        }

        // Trigger HTTP Requests
    }
}

Then my main.js file;

import {HttpClient} from 'aurelia-http-client';
import {EventAggregator} from 'aurelia-event-aggregator';
import {AppState} from 'services/appState';

export function configure(aurelia) {
    const container = aurelia.container;
    const httpClient = container.get(HttpClient);
    const ea = container.get(EventAggregator);
    const appState = container.get(AppState);

    httpClient.configure(config => {
        config.withInterceptor({
            request(request) {
                if(appState.get('authenticate')) {
                    let username = appState.get('username');
                    let password = appState.get('password');
                    request.headers.add("Authorization", "Basic " + btoa(username + ":" + password));
                }
                ea.publish('http-request', request);
                return request;
            },
            requestError(error) {
                ea.publish('http-request-error', error);
                throw error;
            },
            response(response) {
                ea.publish('http-response', response);
                return response;
            },
            responseError(error) {
                ea.publish('http-response-error', error);
                throw error;
            }
        });
    });

    aurelia.use
        .standardConfiguration()
        .developmentLogging()
        .singleton(HttpClient, httpClient);


      aurelia.start().then(() => aurelia.setRoot());
}
Tom
  • 4,257
  • 6
  • 33
  • 49
1

Try creating an actual headers object like this:

this.http.configure((configure) => {
  if(this.username && this.password) {
    configure.withDefaults({
        headers: new Headers({
          'Authorization': 'Basic ' + btoa(this.username + ":" + this.password)
        })
    });
  }
})
Armon Bigham
  • 339
  • 2
  • 14