Home > database >  How to set default header in axios with Typescript
How to set default header in axios with Typescript

Time:11-06

I want to set default header with axios in Typescript. Here is my function:

function setJwt(jwt: string | null) {axios.defaults.headers!.common["x-auth-token"] = jwt;}

This shows the following issue: enter image description here

How to solve that in Typescript?

CodePudding user response:

I succeed to solve the problem. Well, headers property has a Record<string, string> type.

So, we should change the second generic type like this:

enter image description here

We cast to unknown first because we can't reconvert directy the type Record

CodePudding user response:

You can try like below,

function setJwt(jwt: string | null) {

    if (axios.defaults?.headers && axios.defaults.headers.common) {
        axios.defaults.headers.common['x-auth-token'] = jwt;
    }

}
  • Related