Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Aurelia: configure fetch client

Tags:

aurelia

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.

like image 228
Gilbert Nwaiwu Avatar asked Feb 07 '23 02:02

Gilbert Nwaiwu


1 Answers

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

like image 157
Fabio Luz Avatar answered Mar 08 '23 12:03

Fabio Luz