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