Let me give an example first. Frontend sends an API request, and server will reject it and add a reason of the rejection into the response header. In this scenario, Frontend wants to extract the reason from the header in the response interceptor and then navigate to different page depending on the reason.
The code is very straightforward like below.
1export function errorInterceptor(error: AxiosResponse) {
2 if (error.status === 401) {
3 const reason = error.headers['reason'];
4 if (reason === 'bar') {
5 window.location.href = '/#!/foo';
6 }
7 }
8 return Promise.reject(error);
9}
10
11axios.interceptors.response.use(
12 (response: AxiosResponse) => response,
13 errorInterceptor
14);
Unfortunately, the above code will behave unexpectedly. As the highlight code error.headers['reason']
will be undefined
.
As I remember that in Angular JS httpProvider, I can get the header object with rejection.headers()
, so I gave a try the below code.
1export function errorInterceptor(error: AxiosResponse) {
2 if (error.status === 401) {
3 const reason = error.headers('reason');
4 if (reason === 'bar') {
5 window.location.href = '/#!/foo';
6 }
7 }
8 return Promise.reject(error);
9}
10
11axios.interceptors.response.use(
12 (response: AxiosResponse) => response,
13 errorInterceptor
14);
The reason can be extracted now, but it failed in the lint check.
(property) AxiosResponse<any, any>.headers: AxiosResponseHeaders
This expression is not callable.
Type 'AxiosResponseHeaders' has no call signatures.
When I check the error object in the browser inspector, it shows that the header object is like below.
headers: function headersGetter(name)
It took me quite long to find the solution and it work like a charm.
1export function errorInterceptor(error: AxiosError) {
2 if (error.status === 401) {
3 const reason = (error.headers as unknown as IHttpHeadersGetter)('reason');
4 if (reason === 'bar') {
5 window.location.href = '/#!/foo';
6 }
7 }
8 return Promise.reject(error);
9}
10
11axios.interceptors.response.use(
12 (response: AxiosResponse) => response,
13 errorInterceptor
14);
If this post helped you to solve a problem or provided you with new insights, please upvote it and share your experience in the comments below. Your comments can help others who may be facing similar challenges. Thank you!