Axios throws an error stating "Response not defined for 302 status

I am currently using axios in conjunction with TypeScript.

Below is a simple axios interceptor that I have implemented:

// Adding a response interceptor
axios.interceptors.response.use((response: AxiosResponse<any>) => {
  // Processing response data
  return response;
}, (error: any) => {
  // Handling response error
  // In this case, "error.response" is undefined. 
  return Promise.reject(error);
});

My objective is to redirect to another location (specifically an identity server SSO page) when a user is not authenticated.

When a call is made to my API and it returns a 302 status code due to authentication failure, the axios interceptor does not automatically redirect to the appropriate location.

Even though manual redirection would be acceptable, the issue lies with "error.response" returning as undefined.

Therefore, I am facing difficulty in determining how to proceed with the redirection, as the status code cannot be detected without the presence of "error.response".

On inspecting the network tab, the information displayed is as follows:

No response data available in the Response tab...

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

Any insights on what might be going wrong in this scenario?

Answer №1

I have come to understand that the 302 code is managed by the browser. Once a 302 response is received, the browser will fetch the page indicated by the location header and pass it to Axios. The page's HTML can be found in response.data, while the URL to redirect to is available in response.request.responseURL.

Based on this understanding, I have implemented the following code snippet:

axios.post('.', Data)
     .then(response => {
         if (response.status === 200) {
             window.location.href = response.request.responseURL;
         }
     })
     .catch(error => {console.log(error)});

This implementation has proven to be useful for my current needs.

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 TypeScript syntax is similar to Java's "? extends MyClass" when using generics?

How can we indicate the TypeScript equivalent of Java's ? extends MyClass? One possible way to achieve this is: function myFunc <TComponent extends MyBaseClass>(param: ComponentFixture<TComponent>) {} Is there a more concise alternative ...

Utilizing a nested ajax call to pass a value from the first call to the URL of the second ajax call

I am working on implementing live search functionality, where I need to pass an id value obtained from the first ajax call to the second one. Currently, when I type rapidly into the search field, I am able to retrieve the information. However, if I perfor ...

What is the best choice for storing data in my Angular2+ component: an object or an observable?

If I were to create an angular2+ component that fetches data from an API and displays its name, which approach would be considered more idiomatic? Initial Strategy: Using thing as an object In this scenario, the component subscribes to a websocket observ ...

Iterate through the complex array of nested objects and modify the values according to specified conditions

I am currently iterating through an array of objects and then delving into a deeply nested array of objects to search for a specific ID. Once the ID is found, I need to update the status to a particular value and return the entire updated array. Issue: Th ...

"Unlocking the Power of jQuery: A Guide to Accessing XML Child

I'm struggling to extract the xml in its current format. While I can easily retrieve the InventoryResponse, I am facing difficulties when trying to access the child node a:Cost. Despite conducting research, I have been unable to find a solution that w ...

What is the process of using observables in Angular to retrieve a number or variable?

While working on an angular service that calls an API and processes a large amount of data, I encountered an issue. I was trying to count the occurrences of each type in the data and send back that count along with the data itself. However, I found that wh ...

What steps are involved in creating a video playlist with YouTube videos?

Is there a way to create a dynamic video playlist that supports embedded YouTube videos without refreshing the page? If a user clicks on another video, I want the video to change dynamically. You can check out this for an example. Do jPlayer, Video.js, Fl ...

Best approach to inform pages about a variable update in Ionic

Imagine a scenario where we have a page called ListItemPage displaying a list of items: Within the ts file, there is a variable defined as items: any = []; In the html file, we find <ion-item *ngFor="let item of items"> Users can click on a (+ ...

Enabling Cross-Site Request Forgery (CSRF) through Angular's HttpClientModule is causing an error message to appear: TS2552 -

As a novice in front-end development, I am looking to incorporate CSRF tokens into certain requests within a frontend application. The app is built using Angular version 12.2.17, and I am following the guidelines outlined in the Angular documentation: http ...

Comprehend PHP scripts within a separate JavaScript file

$(".btn-delete-news").click(function() { if (!confirm('Are you sure to delete ?')) return false; var idNews = $(this).attr('news-info'); console.log(idNews); $.ajax({ url:"<?php echo Yii::app()->createUrl( ...

Typescript error code TS7053 occurs when an element is detected to have an implicit 'any' type due to an expression of a different type

I encountered an issue with the provided example. I'm uncertain about how to resolve it. Your assistance would be greatly appreciated. type TestValue = { value: string; }; type FirstTest = { type: 'text'; text: TestValue[]; }; typ ...

Transforming class attributes in Typescript

I am facing a situation where I need to alter the type of a variable that stores an object based on certain conditions. Here is the variable in question: class MyClass { public referrers: SelectItemGroup[]; } The issue arises when I only need to add a ...

The element is inherently an 'any' type as the expression of type 'number' does not have the capability to index type 'Object'

Hey there, I'm currently in the process of learning Angular and following along with the Note Mates tutorial on YouTube. However, I've hit a stumbling block as I attempt to implement sorting by relevancy. The issue lies with the code snippet belo ...

500 HTTP error occurred while using Laravel's foreach loop with an AJAX request

Here is the AJAX snippet I am using: $('#absensi').on('show.bs.modal', function (event) { var button = $(event.relatedTarget); var data_kelas = button.data('pkelas'); var id = button.data('pid'); ...

I'm encountering an issue with my Next.js development server at localhost:3001 where all routes are displaying a 404 not found page. What

Currently working on a Next.js dashboard app and encountering an issue where my localhost keeps redirecting me to the 404 page. This has happened before, but I can't recall how I resolved it. Here is the recurring problem: I attempted deleting the .n ...

Sending text content using AJAX

Recently, I've delved into the world of AJAX and JavaScript while working on a project in JSP. My goal is to submit text entered in a textarea using a JavaScript button. The first submit button worked fine initially, but upon posting, I ended up with ...

Typescript: uncertain about the "declaration: true" guideline

Let's say I have a app.ts file: interface IApp {} export class App implements IApp {} If I set declaration to true in tsconfig.json, an error will occur: error TS4019: Implements clause of exported class 'App' has or is using private name ...

What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function. I&a ...

What is the process for assigning a predefined type that has already been declared in the @types/node package?

Is there a way to replace the any type with NetworkInterfaceInfo[] type in this code snippet? Unfortunately, I am unable to import @types/node because of an issue mentioned here: How to fix "@types/node/index.d.ts is not a module"? Here is the o ...

Encountering the ExpressionChangedAfterItHasBeenCheckedError error during Karma testing

Testing out some functionality in one of my components has led me to face an issue. I have set up an observable that is connected to the paramMap of the ActivatedRoute to retrieve a guid from the URL. This data is then processed using switchMap and assigne ...