0
votes

I'm currently working on a project using Aurelia as the front-end framework, and I'm wondering if there's a more eloquent and less redundant way to set the request header in my API services. The following is an example.

In this Post service, I have created a configureHeaders method that I'm calling prior to every API call because, otherwise, I run into the case where the web token has changed but the request header isn't updated. While creating this configureHeaders method is a functional workaround, I have to do it for each of my services, and it's feeling very redundant.

Is there a way to configure the request header application-wide so that I don't have to create a configureHeaders method for each service and call it for each request?

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';

import environment from 'environment';

@inject(HttpClient)
export class Post {

    constructor(http) {
        this.http = http;
    }

    configureHeaders() {
        this.token = window.localStorage.getItem('token') || null;
        this.http = this.http
          .configure(x => {
            x.withBaseUrl(environment.serverBaseURL);
            x.withHeader('Authorization', `Bearer ${this.token}`);
          });       
    }

    getPosts() {
        this.configureHeaders();

        return this.http.get('post')    
        .then(posts => {
            return JSON.parse(posts.response);
        });
    }

}
1
Aurelia has the concept of an HTTP interceptor. Although, the docs don't into much detail on how to use it. An interceptor should allow you to centralize setting headers.R. Richards
@R.Richards perfect, thank you so much.Nick

1 Answers

1
votes

As R.Richards commented, Aurelia's HttpClient Interceptor is what you're after.

Here's a class example - as opposed to object with anonymous functions

1.) Declare the interceptor

import {Interceptor, HttpResponseMessage, RequestMessage} from 'aurelia-http-client'

export class CustomInterceptor implements Interceptor {
  request(request: RequestMessage): RequestMessage {
    //Do request interceptor here
    return request;
  }
  response(response: HttpResponseMessage): HttpResponseMessage{
    //Do response interception here
    return response;
  }
}

2.) Register the interceptor as part of your default http client within your main.js

import {CustomInterceptor} from 'path/to/custom-interceptor'

...
...

http.configure(config => {
  //config stuff here
).withInterceptor(new CustomInterceptor())

This should suit your eloquence!