Creating a custom Angular HTTP interceptor to handle authentication headers

Necessity arises for me to insert a token into the 'Authorization' header with every HTTP request. Thus, I created and implemented an HttpInterceptor:

@Injectable()
export class TokenInterceptor implements HttpInterceptor {

  constructor(public authService: AuthService) {
  }  

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let modifiedReq;
    const token = this.authService.getToken();

    // A clone is needed due to immutability of the HttpRequest.
    if (token) {
      modifiedReq = request.clone();
      modifiedReq.headers.set('Authorization', `Bearer ${token}`);
    }

    return next.handle(modifiedReq ? modifiedReq : request).pipe(tap(() => {
        // do nothing
    },
    (err: any) => {
    if (err instanceof HttpErrorResponse) {
      if (err.status === 0) {
        alert('Error: HTTP status code is 0.');
      }
      if (err.status !== 401) {
        return;
      }
      this.authService.goToLogin();
    }
  }));
 }
}

However, it appears that the header is not being attached to the outgoing request. Where could my mistake lie?

Furthermore, there are instances where the interceptor captures errorcode '0'. What does this signify?

Working with Angular version 8.2.11.

EDIT 1: ------------------------

I also attempted the following approach:

request = request.clone({
            setHeaders: {
                authorization: `Bearer ${token}`
            }
        }); 

Despite these efforts, the header remains unset. The module is correctly registered in app.module as well.

 providers: [{
   provide: HTTP_INTERCEPTORS,
   useClass: TokenInterceptor ,
   multi: true,
 }..

EDIT 2 : ------------------------

https://i.sstatic.net/pJtRK.png

Refer to this image... It's driving me insane.

Answer №1

This is how it's currently functioning for me:

const headersConfig = {
  'Accept': 'application/json', //default headers
};
...

if (token) {
  headersConfig['Authorization'] = `Bearer ${token}`;
}
...

return next
  .handle(request.clone({
     setHeaders: headersConfig
  }))

Answer №2

Perhaps you may have overlooked adding this to your app.module:

  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: TokenInterceptor ,
    multi: true,
  }..

Make sure to finalize it like this:

 return next.handle(modifiedReq);

Answer №3

Mistakes were made. During the update of the clone request, it turns out that Angular actually places the new headers in a field named "lazyUpdate" instead of directly within the headers themselves. The reason for the failed requests was due to other factors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

rxjs - straightforward issue with initiating observables

I'm currently tackling an assignment that involves setting up a basic form with input fields for 'From', 'To', and 'Duration' using rxjs. While it might be easier to just utilize getter / setters, I'm determined to ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

The Node module's package.json does not have a main "exports" defined

After recently adding the zx NPM package to my project, I encountered a puzzling issue. The installation went smoothly, and I proceeded to import it into my code: import { $ } from 'zx' (async () => { await $`mkdir test` })() However, u ...

Using Angular frontend to access Django Admin

Is it possible to integrate Django admin with an Angular frontend? I'm currently using Angular version 8.0 for the frontend and Django for the backend. In my urls.py file, I have added the admin as shown below: from django.urls import path, re_path f ...

What are the steps to retrieve information from your personal server using Astro?

I have successfully set up a NodeJS server using Express and Astro for the frontend, with SSR configured through the Astro adapter for NodeJS. My current challenge is fetching data from the backend, and I am unsure of the correct approach to do so. Below ...

Why does the for loop assign the last iteration of jQuery onclick to all elements?

I've encountered an issue with my code that I'd like to discuss var btns = $('.gotobtn'); $('#'+btns.get(0).id).click(function() { document.querySelector('#navigator').pushPage('directions.html', myInf ...

Setting a border on a specific column in ag-grid is a simple task that can help you customize

I have a table where the first set of columns differs from the rest. I am looking to emphasize this distinction by adding a vertical border on the right side of the specific column to highlight it both in the header and rows. Our setup includes using the ...

Capture line breaks from textarea in a JavaScript variable with the use of PHP

I need help with handling line breaks in text content from a textarea. Currently, I am using PHP to assign the textarea content to a Javascript variable like this: var textareaContent = '<?php echo trim( $_POST['textarea'] ) ?>'; ...

Angular 6: Modifying the code of an external library is effective when using 'ng serve' but not when using 'ng build'

In my current project, I have integrated an external library called ng-select by Bas van den Berg. The library works well, but I needed to make it compatible with the onPush change detection strategy. To achieve this, I had to add a ChangeDetectorRef and u ...

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

I encountered an issue trying to animate an OBJ file in Three.JS, even after successfully loading it into the browser

I have encountered a challenge with scaling and animating an object loaded into my web browser using WebGL. The issue arises when attempting to include animation code within the render( ) loop function, specifically with the 'object' variable whi ...

Allowing Users to Easily Copy CSS ::before Content

Text inserted via pseudo-elements like ::before and ::after cannot be selected or copied. Is there a way to change this behavior? span::before { content: "including this text"; } <p> When the text of this paragraph is selected and copied, ...

By default, use jQuery to load the content of a div

Upon page load, I am looking to display the content within #destiny2. This section includes text and images, as well as additional content for three categories. Initially, the first category should be shown without requiring a click. Subsequently, clicking ...

What is the process for transforming a JSON object into a TypeScript interface?

After receiving a JSON output from an api: { "id": 13, "name": "horst", "cars": [{ "brand": "VW", "maxSpeed": 120, "isWastingGazoline": true ...

Struggling to create an Extension Method for Map<TKey, TValue[]> in TypeScript

As a new Angular/TypeScript user, I am really enjoying using Extension methods. They work well on standard types, but now I am facing an issue while trying to write one for the Map data structure where values are arrays. Unfortunately, it does not seem to ...

What is the proper way to send an AJAX request with the data type set to

I am currently working on creating my own POST request. Below is the function I have written: function sendPost(o) { var h = new XMLHttpRequest(); h.onreadystatechange = requestComplete; function requestComplete() { if (h.readyState = ...

transforming an array into JSON structure using node.js

Hello, I have a list of data that I need to convert into JSON format. Here is an example of how I want the data to look: [ { "slideName": "s0", "imageUrl": "https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b494f0074985 ...

What is the best method to retrieve the audio attributes of the currently playing song using the Spotify Web API?

Check out this link for more information on using the Spotify web API to access audio features of tracks. Hello, I am currently utilizing the Spotify web API to retrieve audio features of a track. However, the API documentation only explains how to obtain ...

Deactivating controls while displaying the loading bar in AngularJS

I'm currently working on a web application using AngularJS. I want to incorporate a loading bar to signify long data load times from the server. To replicate heavy data loads, I am utilizing $timeout to trigger the loadbar when the operation begins a ...

Expanding the functionality of Promise to include progress updates

I had the idea to expand Promise by adding a 'progress' feature in order to track progress while using Promise for my asynchronous tasks. So, I created an extended version of Promise like this: class promisePro extends Promise { constructor ...