私はaurelia-http-client
を使用しています。私の要求に対してインターセプターとヘッダーの両方を使用するのに苦労しています。Aurelia - Aureliaフェッチクライアントでヘッダーを設定する
達成する必要があるのは、
- 各インターセプタ(要求、要求エラー、応答、および応答エラー)は、起動時に
aurelia-event-aggregator
を使用してイベントを送信します。 - ヘッダが情報を含む各要求に追加されますが、私は正しく、イベントを公開するためにインターセプタを持っている唯一の方法はmain.js以下のようなで
aurelia.container
を使用することですページに
に入りました。
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());
}
アプリケーションが初期化した後に私の要求のヘッダーを設定する必要がありますので - 私がやるオンラインほとんどのチュートリアルのような上記の構成でそれを行うことはできません。
代わりに、次のように設定する必要があります。
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);
});
}
}
私はさまざまな方法を試みました。
this.http.configure((configure) => {
if(this.username && this.password) {
configure.withDefaults({
headers: {
'Authorization': 'Basic ' + btoa(this.username + ":" + this.password)
}
});
}
})
しかし、私は私がする必要があるヘッダーを変更するための何かを得る、と私はコメントでmain.js
は、あなただけのこのすべてを行い、独自のクラスで 'HttpClient'をラップして、代わりにそのクラスを注入することはできませんか? –
'configure.withDefault'は静的ヘッダを設定するためだけに使うべきです。ヘッダーが変数に依存する場合は、インターセプターで設定する必要があります。例えば、「要求(request){ request.headers.append( 'Authorization'、appState.token); リターンリクエスト。 } ' –