HttpInterceptor is failing to intercept certain requests

After upgrading to the new version of Angular 8, I encountered an issue where the authorization token is not being sent in the request header for certain requests. Despite checking everything, the problem persists. When inspecting the console, I noticed that the authorization header is missing in some requests.

This code snippet demonstrates how to implement a RequestInterceptor in Angular:

import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpEvent,
  HttpHandler,
  HttpRequest
} from '@angular/common/http';

@Injectable()
export class RequestInterceptor implements HttpInterceptor {
  constructor(private authService: AuthService) {}

  intercept(
    req: HttpRequest,
    next: HttpHandler
  ): Observable<HttpEvent> {
    // Retrieve logged in user if connected
    const userToken = this.authService.getAuthenticatedUser();
    // Verify existing of the user
    if (userToken != null && userToken.bearerToken != null) {
      req = req.clone({
        setHeaders: {
          Authorization: userToken.bearerToken
        }
      });
    }
    return next.handle(req);
  }
}

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    FooterComponent,
    HomeComponent,
    ContactUsComponent,
    NotFoundComponent,
    CartComponent,
    LoginComponent
  ],
  imports: [BrowserModule, AppRoutingModule, CustomModule, LayoutModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Despite implementing the RequestInterceptor, the authorization header is still missing in some requests. Any help would be appreciated.

Answer №1

When setting up your Angular app, remember to import HTTP_INTERCEPTORS and your custom service in the providers array.

<! app.module.ts -->
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { RequestInterceptor } from './your-interceptor-path'

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: RequestInterceptor,
      multi: true
    }
  ]

If you want to clone only the Authorization header into the new HttpRequest, follow these steps:

To ensure proper functionality of your RequestInterceptor service, add the following lines next to the Authorization header clone:

if (!req.headers.has('Content-Type')) {
            req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
        }

req = req.clone({ headers: req.headers.set('Accept', 'application/json') });

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

ngResource/$resource injection was not done correctly

I am currently working on developing a client for an API, and I am encountering an issue with the $resource module not being correctly injected. Despite adding ngResource to the module and passing it into the factory declaration, I am facing an error when ...

Exploring Angular 7: Understanding the HTML5 Fullscreen API and Overcoming Errors

I am currently using Angular 7 and I am trying to implement a fullscreen button in my app. I have utilized the HTML5 Fullscreen API and created two functions for this purpose: openfullscreen() { // Trigger fullscreen console.log('gg'); ...

JavaScript Decoding JSON with varying identifiers

The JSON data provided contains information about different types of vehicles, such as cars, buses, and taxis. { _id:"7654567Bfyuhj678", result:{ CAR:[ [ "myCar1", 12233 ], [ ...

Vue composable yields a string value

I am currently using a Vue composable method that looks like this: import { ref } from 'vue'; const useCalculator = (num1: number, num2: number, operation: string) => { const result = ref(0); switch (operation) { case 'add& ...

Incorporate HTML elements into a React component

Is there a way to render (move) a DOM element into a React Component? I am facing a situation where I have integrated a third-party script into my React project (such as incorporating a live chat widget with a script). This script generates a DOM node when ...

Which is better for event handling: one large event or multiple small events?

What is the preferred pattern and rationale behind it? $myElements.delegate(selector, 'event1 event2', function () { if (event.type === 'event1') { /* Handle event 1 */ } if (event.type === 'event2') { /* Handle event 2 ...

Tips on utilizing boolean assignment in a ternary operator with an optional property that is an array in TypeScript

I'm trying to determine the value of an object property based on whether an optional prop is an array. Here's the scenario: const requestingMultipleDevices = Array.isArray(deviceIds); Then I have this object structure: { data: requestingM ...

Why is my npm installation generating an ERESOLVE error specifically linked to karma-jasmine-html-reporter?

Could someone help me understand this dependency error I encountered while running npm install and provide guidance on how to resolve such errors? View Error Screenshot I am currently using Angular 16, the latest stable version. npm ERR! code ERESOLVE ...

StopDefault and JSON Placement

We have a form that sends data to an external domain using JSONP to avoid cross-domain limitations. Everything is functioning properly except for preventing the default form submission that triggers a page reload. Below is the HTML code for the form: < ...

A superior method for implementing CSS keyframe transitions

Currently, I am utilizing the Rico St.Cruz brilliant query.transit library for my work. However, I need to make some changes involving classes instead of CSS transitions. Although I am not very confident in CSS transitions, I attempted to replace: JS: $ ...

Press the dynamic div element within the frame by utilizing Java Selenium WebDriver

How do I interact with a menuitem in one frame to display a dashboard in another frame? <html> <head> <frameset scrolling="no" framespacing="0" marginwidth="0" marginheight="0" border="0" frameborder="0" rows="98,*"> ...

A jquery class for styling with CSS

I am looking to add a CSS class to a gridview. I attempted to use this style from a reference link, so I implemented the following code snippet: $(function () { $('[ID*=search_data]').on('click', function () { var fromda ...

What is the process for including a field specific to a date in a form?

I need the user to select a month and year. In one column, there will be the days of the month they selected [e.g. 1-30]. Users can then add habits in other columns. I want users to be able to input an 'X' for each habit row on a specific date [e ...

Leverage generic types and allow acceptance of objects with arbitrary keys

Is it possible to allow the Use function argument type to accept any unknown key, as well as correctly type the keys from SomeGeneric? function Example (opt: { valid?: boolean }) { } type SomeGeneric = Parameters<typeof Example>[0] function Use(op ...

Tips for designing a unique CSS ellipse effect for text styling

Hey there! I have a list of titles in a drop-down menu as strings, for example: "Bharat Untitled offer #564", "Bharat Untitled offer #563" The titles are quite long, so we want to display the first eight characters, followed by '...' and then ...

Unable to retrieve data from the $.getJSON method

Using $.getJSON in jQuery, I am retrieving the necessary data from the server. Below is an example of how it is structured: $.getJSON("/dataParser/parseVoltage",function(jsondata, status) { if (status == "error") { console.log("Error occurred whil ...

Even in the absence of the element on the page, the VueJS instance is still being invoked

I am encountering an issue where all my VueJS instances are being executed, even if the element associated with them is not present on the page. Currently, I have defined a mixin as follows: var mixin = { methods: { listEvents(parameters) { ...

Best practices for consuming streams using jQuery

Looking to extract VU meter data from my shoutcast server in a continuous live stream format with the following structure: "0xa5 leftVal rightVal 0xa5 leftVal ..... etc" My goal is to capture and decipher this data using JavaScript (jQuery) for animated ...

An alternative method to confirm the checkbox selection without physically clicking on it

Currently, I'm in the process of creating a basic to-do list and have been attempting to connect the task with its corresponding checkbox. My goal is for the checkbox to automatically be checked when the task is clicked. Instead of using HTML to add ...

Ways to differentiate between a desktop browser width of 1024px and a tablet width of 1024px with the help of jquery

So here's the issue I'm dealing with: I have scroll-based animation functions set up for desktop browsers, and different animations in place for tablet browsers. The challenge is to make these functions work on a desktop with a 1024px dimension. ...