Intercepting 401 with Angular 5 HTTP Interceptor recognizes it as status code 0

One issue I am currently facing is the inability to intercept a 401 status and redirect to the login page, which is a common practice in most applications. My interceptor code seems pretty standard:


        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            request = request.clone({
                withCredentials: true
            });

            return next.handle(request)
                .pipe(
                    retry(0),
                    takeUntil(this.httpCancelService.onCancelPendingRequests()), // cancels out pending requests on route change
                    catchError((error: HttpErrorResponse) => {
                        if (error.status === 401) {
                            this.authenticationService.logout(); // logout in case of 401     
                        } else if (request.url.indexOf("assets") == -1) {
                            this.alertService.error('An unexpected error occurred, please try again later');
                        }

                        return throwError(errorMessage);
                    })
                )
        }
    

Although the browser correctly captures the request as a 401 in the Network tab, within this Angular interceptor, 'error.status' returns as '0' and 'error.message' shows as 'Unknown Error'.

Answer №1

If you encounter status code 0, it is likely due to a CORS error. This occurs when the backend server does not include the Access-Control-Allow-Origin header in its response. Once the backend configuration is corrected, you should be able to retrieve the specific error code.

Answer №2

executeIntercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError((error: HttpErrorResponse) => {
                if ((error.status === 401)) {
                    console.log("Handling HTTP 401 error")
                }
                return throwError(error);
            })
        );
}

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

What is the best way to adjust the output size for ngx-webcam?

I am looking to determine the smallest possible size for an image that is captured. From my testing with ngx-webcam, I have found that I can adjust the minimum height of the output image based on the display height of the webcam. Is there a method to set ...

Guide to utilizing the Angular Material 2 documentation without an internet connection

Is there a way to access the Angular Material 2 documentation offline? I would like to have it available without needing an internet connection. What alternatives or solutions are there for this? ...

Angular application triggering multiple subscribe method calls upon a link click event

Here is the code for my navbar component: <li *ngFor="let item of menu"> <a *ngSwitchCase="'link'" routerLinkActive="active" [routerLink]="item.routerLink" (click)="Navigation(item.title)&q ...

Ways to create a vertical bottom-up tree view using d3.js

I am trying to create a reverse tree view, starting from the bottom and moving up. What modifications do I need to make? Here is the link to my JS Fiddle: ...

Displaying the age figure in JSX code with a red and bold formatting

I have a webpage with a button labeled "Increase Age". Every time this button is clicked, the person's age increases. How can I ensure that once the age surpasses 10, it is displayed in bold text on a red background? This should be implemented below t ...

I'm interested in developing a feature that monitors a specific attribute and triggers a function once that attribute hits the value of 100

I am working on a function that will refresh the view once the percentage changes reaches 100: The value is stored in this variable: this.uploadPercent = task.percentageChanges(); This is the function I plan to implement : refreshView(){ Once this.uplo ...

What is the best way to store a range object obtained from getSelection in order to recreate it on a separate page load?

My goal is to develop a web application that enables users to highlight selected text on a webpage with the click of a button. I want these highlights to persist even when the user returns to the page. So far, I have achieved: var selectedRange = documen ...

The HTML grid is causing an irritating excess space on the right side of my website

After brainstorming an idea, I decided to create this website for testing purposes. However, the grid layout seems to be causing an unwanted margin on the right side of the page that is not associated with any HTML tag, disrupting the zoom functionality. ...

Accessing a TypeScript variable in Angular2 and binding it to the HTML DOM

While I have experience with AngularJS, delving into Angular2 has proven to be a new challenge for me. Understanding the ropes is still a work in progress. In my list of files, there's a home.ts and a home.html Within my home.ts, this snippet reside ...

The module 'AppModule' has unexpectedly declared a value of 'Component' that was not anticipated

Recently, I've been working on transitioning my application to the new angular2 webpack rc5 setup. I have successfully generated the app module using ng cli migration. However, I am facing an issue while trying to integrate a component from my own li ...

The JWT Token is not being sent to the allowedDomain or whitelistedDomains in auth0/angular-jwt due to a configuration issue involving Regexp

Currently, I am utilizing the auth0/angular-jwt library to inject JWT tokens into my application. The documentation for this library suggests that configuration can be achieved by using strings or RegExp for specifying allowed domains. However, upon implem ...

Adjust the positioning of two divs on mobile devices

My website has two main divs, one on the left and one on the right. The left div is styled with the classes: col-md-3 left_side And the right div with: col-md-9 right_side In the CSS file, the left_side and right_side classes only have padding, without a ...

Having difficulty locating the identification number of an item within the HTML coding

I'm currently trying to locate the ID of the "proceed to checkout" button for a bot that I am developing for my mother on the Best Buy website. However, it seems like the button's ID is hidden and I'm unable to determine how to uncover it. A ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

Obtaining distinct form control values for replicated form fields with Angular

Issue with Dynamic Form Duplicates: I am currently working with a reactive form that has two fields - name and value. There is an add button that duplicates the form by copying these fields. The challenge I am facing is with updating the values of the dup ...

Show the button only when the text is updated

Is there a way to display a button only when the quantity of items in the cart changes, similar to the eBay shopping cart feature? I was able to implement it but it's not functioning as expected. Here is the link to what I have so far. Does anyone kno ...

Guide to successfully submitting an Angular form that includes a nested component

I have developed a custom dateTime component for my application. I am currently facing an issue where I need to integrate this component within a formGroup in a separate component. Despite several attempts, I am unable to display the data from the child fo ...

How to Access a div from another website using jQuery

I have a question. How can I call a div from another website using JavaScript? Here is the page: Now, I want to call the <div id="testa"> in another page. The other page is called Otherpage.html: jQuery(function($){ $(&ap ...

Regularly fetching images from PHP page

Recently, I encountered a challenge with a PHP page that retrieves arguments from the URL to generate an image. The image type (png, gif, etc.) is unknown. Typically, the page is used to embed the image in a standard HTML page like so: <img src="page.p ...

What is the best way to eliminate the space between the website's border and the image?

Is there a way to eliminate the space between the left and right borders? I want the picture to fill 100% of the browser window. https://i.stack.imgur.com/gqgOs.png img.test { display: block; outline: 0px; padding: 0px; margin: 0px; } <img c ...