4

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.

Gilbert Nwaiwu
  • 687
  • 2
  • 13
  • 37

1 Answers1

8

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

Fabio
  • 11,892
  • 1
  • 25
  • 41
  • How would you configure the api url for each specific url? – Diego Gallegos May 04 '16 at 21:28
  • You don't have to configure the whole url for each call. You could configure the base url, for instance`http://localhost:8080/api/`. Then, you just have to call `this.http.fetch('something')`. The final URL would be -> `http://localhost:8080/api/something` – Fabio May 05 '16 at 13:39
  • I tested it out but got an error "HttpClient" is not defined. I then added "import {HttpClient} from 'aurelia-fetch-client'" but now the error is "TypeError: window.localStorpassword is undefined". I use it for getting my token from local storage – Gilbert Nwaiwu May 07 '16 at 11:59
  • you should write a function that checks if the localStorageProperty is undefined. Something like `if (window.localStorage.token !== undefined)... ` – Fabio May 07 '16 at 20:47