Obtaining Axios response header in a Typescript environment

I am currently working on a rest call that may return a header that I need to store. In order to do this, I have to first check if the header is present before storing it.

Here is how I approached it:

private getHeader(response: AxiosResponse) {
    if (response.headers.has('myheader')) {
      storeHeader(response.headers['myheader']);
    }
 }

However, when trying to execute response.headers.has, TypeScript gives me the following errors:

TS18049: 'response.headers.has' is possibly 'null' or 'undefined'.
TS2723: Cannot invoke an object which is possibly 'null' or 'undefined'.
TS2349: This expression is not callable. Not all constituents of type 'string | number | boolean | AxiosHeaders | string[] | ((header: string, matcher?: true | AxiosHeaderMatcher | undefined) => boolean)' are callable. Type 'string' has no call signatures.

Answer №1

The headers property in AxiosResponse is a combination of RawAxiosResponseHeaders or AxiosResponseHeaders, while AxiosResponseHeaders is a mix of RawAxiosResponseHeaders and AxiosHeaders.

Since the method has is part of the AxiosHeaders class, it's necessary to specify that response.headers should be limited to AxiosHeaders before using has. This can be achieved by checking if headers instanceof AxiosHeaders first.

const headers = response.headers
if (headers instanceof AxiosHeaders && headers.has('myheader')) {
    storeHeader(headers['myheader']);
}

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

Can PassportLocalDocument and PaginateModel coexist within the same framework?

I am new to TypeScript and NestJS, looking to implement a pagination feature for all models in my application. Currently using NestJS with Mongoose for the API project. Here is an example of the user schema: export const UserSchema = new mongoose.Schema( ...

Utilizing Typescript for manipulation of Javascript objects

Currently, I am working on a project using Node.js. Within one of my JavaScript files, I have the following object: function Person { this.name = 'Peter', this.lastname = 'Cesar', this.age = 23 } I am trying to create an instanc ...

Exploring the possibilities of TypeScript/angularJS in HTTP GET requests

I am a beginner in typescript and angular.js, and I am facing difficulties with an http get request. I rely on DefinitelyTyped for angular's type definitions. This is what my controller code looks like: module game.Controller { 'use strict& ...

Move forward state using navigateByUrl in Angular

I am looking to send data when changing the view using navigateByUrl like this: this.router.navigateByUrl(url, {state: {hello: "world"}}); Once in the next view, my goal is to simply log the hello attribute like so: constructor(public router: Router) { ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

What is the best way to eliminate any extra spaces from a string using typescript?

Currently in my Angular 5 project, I am encountering an issue with using the .trim() function in TypeScript on a string. Despite implementing it as shown below, no whitespace is being removed and also there are no error messages appearing: this.maintabinf ...

What is the reason behind Typescript flagging a potential undefined value when checking for array length using a greater than comparison but not with an

Consider the following excerpt from a React component: const AccountInformation = (props: { readonly accountData: AccountData | undefined | null }) => { const hasMultipleAccounts: boolean = props.accountData?.customerAccounts?.length === 1 ? false : t ...

Analyze the information presented in an HTML table and determine the correct response in a Q&A quiz application

I need to compare each row with a specific row and highlight the border accordingly: <table *ngFor="let Question from Questions| paginate: { itemsPerPage: 1, currentPage: p }"> <tr><td>emp.question</td></tr> <tr> ...

What is the reason for requiring that the value type in a map must be uniform?

When using TypeScript, I expect the map type to be either a number or string, but unfortunately, an error is being reported. Click here for the Playground const map: Map<string, string | number> = new Map([ [ '1', &apo ...

Creating a unique custom pipe in Angular 5

Recently, I started learning Angular and encountered an issue that I'm struggling with. I am trying to develop a custom pipe that can convert decimal codes into base64 images and then display them in views. Even though I have the complete code to add ...

Is there a way to verify if a user taps outside a component in react-native?

I have implemented a custom select feature, but I am facing an issue with closing it when clicking outside the select or options. The "button" is essentially a TouchableOpacity, and upon clicking on it, the list of options appears. Currently, I can only cl ...

Can I integrate @types/pkg into my custom library to automatically have types included?

Imagine I am creating a library that utilizes types from the Definitely Typed repository (such as @types/pkg). Would it be feasible for my package to automatically include these types when installed, eliminating the need for consumers to separately instal ...

Showing canvas lines while dragging (using only plain JavaScript, with React.JS if needed)

Is there a way to add lines with two clicks and have them visible while moving the mouse? The line should only be drawn when clicking the left mouse button. Any suggestions on how I can modify my code to achieve this functionality? Currently, the lines are ...

When a button is clicked in (Angular), it will trigger the highlighting of another button as a result of a value being modified in an array. Want to know the

Currently in the process of developing a website with Angular, I've encountered an unusual bug. The issue arises when using an *ngFor div to generate twelve buttons. <div *ngFor = "let color of colors; let i = index" style = "display ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

Removing a value from a hashmap using Typescript - what is the best way to do it?

After successfully implementing a hashmap in typescript following a helpful post, I am facing an issue with removing something from the hashmap. TypeScript hashmap/dictionary interface To add a key to the keys field of my abstract Input class's hash ...

Setting a default value for NULL property in TypeScript

Trying to establish a default value for all NULL objects has been quite the challenge. The current code looks like this: private setDisplayAmount(summaries: summary[]): void { summaries.map(t => { // performing some operations, and then... ...

React Axios has an issue with handling empty responses from the server due

Currently developing my inaugural MERN app. Encountering an issue where the body content seems to be lost when attempting to call my backend API, despite successful interaction through Postman. Suspecting a CORS-related error on my end. Displayed below is ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...