Aurelia: configure fetch client

戏子无情 提交于 2019-12-30 10:36:22

问题


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).

Is there a way to configure the fetch client once somewhere instead of rewriting the interceptor code in each viewModel.


回答1:


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);

Now, you just have to inject the HttpClient to get the instance configured above.

@inject(HttpClient)
export class MyViewModel {
}

More information at https://github.com/aurelia/fetch-client/blob/master/doc/article/en-US/http-services.md



来源:https://stackoverflow.com/questions/36999448/aurelia-configure-fetch-client

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!