Aurelia:配置获取客户端 [英] Aurelia: configure fetch client
问题描述
我使用Aurelia的获取客户端与服务器进行通信.在每个使用fetch客户端的viewModel中,我必须将其配置为使用拦截器发送自定义标头(令牌)的客户端.
I use Aurelia's fetch client to communicate with my server. In every viewModel using the fetch client I have to configure it the client to use an interceptor to send a custom header(a token).
有没有一种方法可以在某处配置一次获取客户端,而不是在每个viewModel中重写拦截器代码.
Is there a way to configure the fetch client once somewhere instead of rewriting the interceptor code in each viewModel.
推荐答案
您可以将配置放入 main.js 文件中.像这样:
You could put the configuration in the main.js file. Like this:
...
aurelia.use
.standardConfiguration()
.developmentLogging();
let container = aurelia.container;
let http = new HttpClient();
http.configure(config => {
config
.useStandardConfiguration()
.withBaseUrl('http://localhost:8080/api/')
.withDefaults({
headers: {
'Authorization': tokenVariable // <---- your magic here
}
})
.withInterceptor({
request(request) {
console.log(`Requesting ${request.method} ${request.url}`);
return request;
},
response(response) {
console.log(`Received ${response.status} ${response.url}`);
}
});
});
container.registerInstance(HttpClient, http);
现在,您只需要注入HttpClient即可获得上面配置的实例.
Now, you just have to inject the HttpClient to get the instance configured above.
@inject(HttpClient)
export class MyViewModel {
}
更多信息,请参见 https ://github.com/aurelia/fetch-client/blob/master/doc/article/en-US/http-services.md
这篇关于Aurelia:配置获取客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!