Within my application, I am making multiple HTTP requests that all require an authentication header with an access token (along with other header values). I have defined a header variable of type HttpHeaders
(refer to code#1) to be used as follows:
this.http.get(this.myUrl, { headers: this.headers})
.In my scenario, the token needs to be refreshed periodically and I want to update the header with the latest token.
In my code, there is a refresh function that is responsible for obtaining a new token and replacing the old token in the HTTP header with the updated one.
Initially, I attempted to utilize the provided set() method (see code#2). However, this approach resulted in adding a new value to the header instead of replacing it, leading to duplicates.
Subsequently, I tried using the delete() method (see code#3) to remove the Authorization value first and then using the append() method to insert the new token. Unfortunately, this also did not achieve the desired outcome.
My final attempt involved solely using the delete() method (see code#4).
Code Samples
code#1:
headers = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json');
code#2:
this.headers = this.headers
.set('Authorization', 'Bearer ' + access_token);
code#3:
this.headers = this.headers.delete('Authorization');
this.headers = this.headers.append('Authorization','Bearer ' + access_token);
code#4:
this.headers = this.headers.delete('Authorization','Bearer ' + access_token);
Results
My expectation was that the value of the header
({'Authorization', 'Bearer ' + access_token})
would be replaced (in the 1st approach). Instead, the actual result showed that it was just appended:
{"Authorization", "Bearer access_token-old"}
{"Authorization", "Bearer access_token-new"}
As for the second approach, the goal was to delete and append a new value, however, it still ended up adding two values:
{"Authorization", undefined}
{"Authorization", "Bearer access_token-new"}
The last approach yielded the same output as the first approach, rather than simply replacing the value.
Is there any method available to seamlessly replace the access_token/value in
{'Authorization','Bearer ' + access_token}
?