Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Types prevent adding new values to headers #5034

Open
dartess opened this issue Oct 6, 2022 · 61 comments
Open

Types prevent adding new values to headers #5034

dartess opened this issue Oct 6, 2022 · 61 comments

Comments

@dartess
Copy link

dartess commented Oct 6, 2022

Describe the bug

Types prevent adding new values to headers

To Reproduce

function getRequestConfig(options: AxiosRequestConfig): AxiosRequestConfig {
  return {
    ...options,
    headers: {
      ...options.headers,
      Authorization: `Bearer ...`,
    },
  };
}
TS2322: Type '{ Authorization: string; get?: AxiosHeaders | undefined; delete?: AxiosHeaders | undefined; head?: AxiosHeaders | undefined; options?: AxiosHeaders | undefined; ... 6 more ...; common?: AxiosHeaders | undefined; }' is not assignable to type 'Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>'.
   Property 'get' is incompatible with index signature.
     Type 'AxiosHeaders' is not assignable to type 'AxiosHeaderValue | undefined'. 

Expected behavior

Everything is working

Environment

  • Axios Version 1.0.0
@visoft
Copy link

visoft commented Oct 7, 2022

Still an issue in 1.1.2

@salmannotkhan
Copy link
Contributor

salmannotkhan commented Oct 8, 2022

I have fixed it by changing

type RawAxiosHeaders = Record<string, AxiosHeaderValue>;

To

type RawAxiosHeaders = Record<string, AxiosHeaderValue | AxiosHeaders>;

In index.d.ts
Should I create Pull Request for this?

@amirfahmideh
Copy link

I have same issue after upgrading to 1.1.2, Is there any solution behind downgrade ?!

@amirfahmideh
Copy link

amirfahmideh commented Oct 11, 2022

I fix my issue with how I set my header
axios.interceptors.request.use( function (config) { if (config && config.headers) { config.headers["Authorization"] = "bearer myTokenFromStore"; config.headers["Content-Type"] = "application/json"; return config; }, function (error) { return Promise.reject(error); } );

@jasonsaayman
Copy link
Member

Will PR this tonight unless @salmannotkhan wants to

@salmannotkhan
Copy link
Contributor

I would love to create PR :)

@salmannotkhan
Copy link
Contributor

Can you assign this to me?

salmannotkhan added a commit to salmannotkhan/axios that referenced this issue Oct 11, 2022
jasonsaayman added a commit that referenced this issue Oct 13, 2022
fixes issue #5034

Co-authored-by: Jay <jasonsaayman@gmail.com>
@lucasgadams
Copy link

I'm having this issue. What is the status?

@salmannotkhan
Copy link
Contributor

Already fixed. Can we close this issue @jasonsaayman?

@ndjerrou
Copy link

Still the same with the 1.1.13 version...

@ndjerrou
Copy link

ndjerrou commented Nov 21, 2022

I got this :

Error: Type '{ Authorization: string; }' is not assignable to type 'Partial<HeadersDefaults> | Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders> | undefined'.

Axios : version 1.1.3

const client = axios.create({ baseURL: API_URL, timeout: 1000, headers: {Authorization: ``Bearer ${OAUTH_TOKEN}``}, });

what's wrong ?

@chubo274
Copy link

i have this issue on Axios version: 1.2.1

when i use:
config: AxiosRequestConfig;
config.headers.Authorization = Bearer ${token};

Property 'Authorization' does not exist on type 'AxiosHeaders | Partial<RawAxiosHeaders & MethodsHeaders & CommonHeaders>'.
Property 'Authorization' does not exist on type 'AxiosHeaders'.ts(2339)

@pieterh
Copy link

pieterh commented Dec 30, 2022

I seem to able to fix it by changing
config.headers.Authorization = Bearer ${token};
to
(config.headers as AxiosHeaders).set("Authorization", Bearer ${token});

possibly you need to import the AxiosHeaders
import {AxiosHeaders } from 'axios';

@saitoChen
Copy link

I seem to able to fix it by changing config.headers.Authorization = Bearer ${token}; to (config.headers as AxiosHeaders).set("Authorization", Bearer ${token});

possibly you need to import the AxiosHeaders import {AxiosHeaders } from 'axios';

That's really helpful!
Thanks bro!

@xgenem
Copy link

xgenem commented Jan 2, 2023

Wow this is a weird one

@trainoasis
Copy link

Similar issue on v1.2.2 which ends in Type 'AxiosHeaderSetter' is not assignable to type 'AxiosHeaderValue | undefined' .. solved by casting ..

headers: {
    ...defaultHeaders,
    ...getAuthHeaders(),
    ...(config.headers as RawAxiosRequestHeaders), // <<<< this here
  },

@xsjcTony
Copy link

xsjcTony commented Jan 4, 2023

Any news on this? still has issue with 1.2.2

@pieterh
Copy link

pieterh commented Jan 4, 2023

Hi, did you try the workaround I mentioned earlier? It works for 1.2.2
Using the workaround would release the pressure on this problem. At least you can continue while the fix is being made.

@xsjcTony
Copy link

xsjcTony commented Jan 4, 2023

@pieterh Ah I just put an @ts-expect-error comment there with the link of this issue, I personally don't like to cast the type so I'd rather wait for the fix. Thanks for the workaround anyway.

@WangJincheng4869
Copy link

这个问题出现的根源是axios出现的bug还是说typescript的设计就是存在缺陷的,不像Java那样完善,在使用typescript开发过程中,类似的问题出现的频率较高。我感觉typescript开发组应该注意一下这个问题。
image

@thomastvedt
Copy link

axiosInstance.interceptors.request.use(async function (config) {
  config.withCredentials = true;
  const token = await getAccessToken();

  if (token?.bearerToken) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token.bearerToken}`,
    };
  }

  return config;
});

this worked before, but not after upgrading to v1.2.2.

workaround as suggested by @xsjcTony

axiosInstance.interceptors.request.use(async function (config) {
  config.withCredentials = true;
  const token = await getAccessToken();

  if (token?.bearerToken) {
    // TODO: axios bug workaround, ref: https://github.com/axios/axios/issues/5034
    // @ts-expect-error
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token.bearerToken}`,
    };
  }

  return config;
});

@ts-expect-error is a special comment that instructs the compiler to ignore any issues it finds when processing the next line.

@xsjcTony
Copy link

Seems still an issue in v1.2.3

@samyarkd
Copy link

I was able to fix it like this

apiClient.interceptors.request.use((config) => {
  const token = getToken()

  if (token) {
    ;(config.headers as AxiosHeaders).set('Authorization', `Bearer ${token}`)
  }
  return config
})

Is this a common pattern?

@pieterh
Copy link

pieterh commented Jan 21, 2023

I think that casting to AxiosHeaders and using 'set', is a much better and sustainable solution then suppressing an unspecified error on the next line.
If in the future the problem is gone and replaced with an other error... That future error is also suppressed and it will be unnoticed.

@xsjcTony
Copy link

xsjcTony commented Jan 21, 2023

I don't stand with casting. Casting, for me, just means you lie to the compiler.

@ts-expect-error works differently from @ts-ignore, if the problem has been fixed, @ts-expect-error will raise an error since it's not being used. Unless this bug has been fixed and another issue comes up in the same version, and at the same line of the code, then it's another story. And I personally don't think this will happen.

@pieterh
Copy link

pieterh commented Jan 21, 2023

Interesting insight. Thanks. The casting is indeed a temp solution.

@xsjcTony
Copy link

@DigitalBrainJS Hey, thanks for trying that out.
The code triggering the error is ...config.headers.
I've updated your codesandbox and the error comes out:
Snipaste_2023-01-26_05-23-41
Edit axios-types-test (forked)

@xsjcTony
Copy link

Fixed in v1.2.5 🎉

@SpiffGreen
Copy link

I did a pretty rough setup to make this work:

interface iAxiosHeaders extends AxiosHeaders {
  Authorization: string
}

instance.interceptors.request.use((request: AxiosRequestConfig) => {
    request.headers = ({
      Authorization: `Bearer ${token}`,
      ...request.headers
    }) as iAxiosHeaders
    return request;
  });

@DigitalBrainJS
Copy link
Collaborator

DigitalBrainJS commented Jan 30, 2023

Cheat Sheet (v1.2.6):

axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers.setAuthorization(`Bearer ${token}`)

    return request;
});
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers.set('Authorization', `Bearer ${token}`);

    return request;
});
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers.set({
        Authorization: `Bearer ${token}`
    })

    return request;
});
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers = {
        Authorization: `Bearer ${token}`,
        ...request.headers
    } as AxiosRequestHeaders;

    return request;
});
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers = new AxiosHeaders({
        Authorization: `Bearer ${token}`
    });

    return request;
});
axios.interceptors.request.use((request: InternalAxiosRequestConfig) => {
    request.headers = AxiosHeaders.concat(request.headers, {
        Authorization: `Bearer ${token}`
    });

    return request;
});
axios.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  config.headers.myHeader = 123;

  return config;
});

@DigitalBrainJS DigitalBrainJS pinned this issue Feb 1, 2023
@thomastvedt
Copy link

This is fixed now, I guess the issue can be closed?

Note that this still doesn't work:

  if (token?.bearerToken) {
    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token.bearerToken}`,
    };
  }

But this works:

  if (token?.bearerToken) {
    config.headers.setAuthorization(`Bearer ${token.bearerToken}`);
  }

@Xefexium
Copy link

This is still an issue in axios version 1.3.3

@mikolaszko
Copy link

This is still an issue in version 1.3.4 but now @xgenem 's original solution is working

@yogeshnikam671
Copy link

Is this issue solved ? Should this issue be closed ?

@jewseppi
Copy link

jewseppi commented Mar 2, 2023

Yes, still an issue 👎
None of the solutions above seem to work either.

@jewseppi
Copy link

jewseppi commented Mar 3, 2023

I was able to resolve the issue by casting the response like so:

function = (
  config: InternalAxiosRequestConfig,
  token: string
) => ({
  ...config,
  headers: {
    ...config.headers,
    Authorization: `Bearer ${token}`,
  } as AxiosRequestHeaders,
});

@yair-rodriguez
Copy link

Still an issue in v1.3.4.

Captura de pantalla 2023-03-15 a la(s) 12 50 33

The errors I get:

Type '{ Authorization: string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; 'Content-Type'?: ContentType | undefined; }' is not assignable to type 'AxiosRequestHeaders'.
Type '{ Authorization: string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; 'Content-Type'?: ContentType | undefined; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.ts(2322)

@dartess
Copy link
Author

dartess commented Apr 3, 2023

The problem described in the first post has ceased to be reproduced. I'm not sure if I need to close the issue if the error persists in some scenarios.

@arthurfiorette
Copy link
Contributor

I think this should be unpinned, I'm at v1.4.0 and i'm not having any issues.

@souvikjanatw
Copy link

The issue is still there in v1.4.0 with the type of config

axios.interceptors.request.use((config) => {
    return {
      ...config,
      headers: {
        ...config.headers,
        Authorization: "Bearer " + defaultJwtToken(),
      },
    };
  });

@brascene
Copy link

Using v1.4.0 and got rid of type issue with this:

Screenshot 2023-05-11 at 16 49 25

@cristan
Copy link

cristan commented May 24, 2023

With me, the compilation error was fixed by instead of doing this:

const headers = {"HeaderName": "HeaderValue"}

To do this:

const headers = new AxiosHeaders({"HeaderName": "HeaderValue"})

@souvikjanatw
Copy link

The issue is still there in v1.4.0 with the type of config

axios.interceptors.request.use((config) => {
    return {
      ...config,
      headers: {
        ...config.headers,
        Authorization: "Bearer " + defaultJwtToken(),
      },
    };
  });

Updated the above implementation to the following to fix the issue:

axios.interceptors.request.use((config) => {
    config.headers.Authorization = `Bearer ${defaultJwtToken()}`;
    return config;
 });

@WheelerCC
Copy link

WheelerCC commented Jul 21, 2023

Still experiencing some weirdness on 1.4.0 when using spread syntax instead of the set method.

function generateSignedDigitalSignatureHeaders(req: AxiosRequestConfig, service: EbayService): SignedDigitalSignatureHeaders {
  // Generating a hash of the request payload for 'content-digest'
  const payload = req.params ?? {};
  const payloadBuffer: Buffer = Buffer.from(typeof payload === 'string' ? payload : JSON.stringify(payload));
  const payloadHash = createHash('sha256').update(payloadBuffer).digest('base64');

  // Creating the 'digital signature' header fields used to generate the actual signature
  const digitalSignatureHeaders: DigitalSignatureHeaders = {
    'x-ebay-signature-key': service.public_key_jwe,
    'content-digest': `sha-256'=:${payloadHash}:`,
    'signature-input': `sig1=(${signatureInputParams.map((param) => `"${param}"`).join(' ')});created=${getUnixTimestamp()}`,
  };

  const signatureComponents: SignatureComponents = {
    method: req.method!.toUpperCase(),
    authority: 'apiz.ebay.com',
    path: '/sell/finances/v1/transaction',
  };

  // Creating the actual signature of our digital signature headers, and adding both it and the headers to the request
  return {
    ...digitalSignatureHeaders,
    'signature': generateSignature(digitalSignatureHeaders, service.private_key, signatureComponents),
  };
}
axios.interceptors.request.use((req: AxiosRequestConfig) => {
  req.headers = {
    ...(req.headers ?? {}),
    ...generateSignedDigitalSignatureHeaders(req, service),
  };

The above results in

Type '{ signature: string; 'x-ebay-signature-key': string; 'content-digest': string; 'signature-input': string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeader...' is not assignable to type 'AxiosRequestHeaders'.
  Type '{ signature: string; 'x-ebay-signature-key': string; 'content-digest': string; 'signature-input': string; Accept?: AxiosHeaderValue | undefined; "Content-Length"?: AxiosHeaderValue | undefined; "User-Agent"?: AxiosHeaderValue | undefined; "Content-Encoding"?: AxiosHeaderValue | undefined; Authorization?: AxiosHeader...' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more.

The workaround below has the desired effect:

axios.interceptors.request.use((req: InternalAxiosRequestConfig) => {
  req.headers.set({...generateSignedDigitalSignatureHeaders(req, service)});
  return req;
});

Whilst the error message is logical and I'm fine using .set(), I'm just ditto'ing the others as it's still a change in behaviour (this didn't present any errors before updating to a newer version)

@Aeolun
Copy link

Aeolun commented Jul 26, 2023

I realize this isn't strictly related to this issue, but I didn't find any other that gets closer.

Why does headers need to be an AxiosHeaders object in the first place? I used to be able to just feed it any Record<string,string> object, and things would be fine, but now I need to cast every single object with headers -no matter how simple- into an AxiosHeaders object.

@arthurfiorette
Copy link
Contributor

@DigitalBrainJS Do we really have any requirements regarding AxiosHeaders being a class and not just a Record<string, string>? I feel this has been giving too much trouble to users...

@federicogomezlara
Copy link

I have a related issue. When I use my Axios custom instance, I can set any headers, even custom ones, and they work, however when attaching an Authorization header, it's ignored

const { data } = await axiosInstance({
      method: 'post',
      url: `/auth/app/profile-image`,
      data: formData,
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'multipart/form-data',
        'XTest-Header': 'test'
      }
    })

Logs the following

 LOG  url /auth/app/profile-image
LOG  headers {"Accept": "application/json, text/plain, */*", "Content-Type": "multipart/form-data", "XTest-Header": "test"}

I attach this Authorization header through a request interceptor like most people, but on this specific case the interceptor won't attach it and I need to do it manually, however it gets ignored & not added

@eduardo-spagna
Copy link

I my case, i use an AxiosResponse object to test my code.

const mockedResponse: AxiosResponse = { data: {}, status: 200, statusText: 'OK', headers: {}, config: { headers: new AxiosHeaders() }, }

It works for me.

@janusqa
Copy link

janusqa commented Sep 26, 2023

axios 1.5.0
Selection_008
How can i fix it.

For now i am doing

error.config.headers['X-XSRF-TOKEN'] = getCookie(XSRF_COOKIE);
error.config.headers[ 'Authorization' ] = `Bearer ${token}`;

@xgenem
Copy link

xgenem commented Oct 4, 2023

October 4, 2023 my updated solution:

API.interceptors.request.use(async request => {
  const token = useAuthStore.getState().token

  if (!token) {
    return request
  }

  request.headers = Object.assign(request.headers, {
    Authorization: `Bearer ${token}`,
  })

  return request
})

Edit: Above works assuming you don't previously set Authorization in your target object (which is the request.headers).

Edit: The following code works axios@1.51

config.headers.setAuthorization(`Bearer ${token}`);

@calavikevin
Copy link

calavikevin commented Nov 2, 2023

You can use the following ways to set headers:

Example for interceptors:

import axios, { AxiosRequestConfig, AxiosHeaders } from 'axios';

const instance = axios.create();
instance.interceptors.request.use((config: AxiosRequestConfig) => {
  const customHeaders = { ...config.headers } as AxiosHeaders;
  
  customHeaders['Authorization'] = `Bearer ...`;

  return {
    ...configs,
    headers: customHeaders,
  };
});

NOTE: I tried "set" and "setAuthorization" but the headers do not have these 2 functions and give an error that these 2 methods are not a function.


axios@1.6.0

@elderdog
Copy link

elderdog commented Dec 6, 2023

I'm using axios@1.6.2, and I get rid of this error by invoking config.headers.concat method like this:

import axios from 'axios'

const instance = axios.create()

instance.interceptors.request.use(config => {
  const customHeaders = {
    'X-Foo': 'foo',
    'X-Bar': 'bar'
  }

  config.headers = config.headers.concat(customHeaders as Record<string, string>)

  return config
})

Instance of AxiosRequestHeaders has a concat method.

@guda-art
Copy link

guda-art commented Dec 25, 2023

The reason for this issue is that we should not rewrite the pointers of headers, as some fields in the declaration file are mandatory rather than optional

export class AxiosHeaders {
  constructor(
      headers?: RawAxiosHeaders | AxiosHeaders | string
  );

  [key: string]: any;

  set(headerName?: string, value?: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  set(headers?: RawAxiosHeaders | AxiosHeaders | string, rewrite?: boolean): AxiosHeaders;

  get(headerName: string, parser: RegExp): RegExpExecArray | null;
  get(headerName: string, matcher?: true | AxiosHeaderParser): AxiosHeaderValue;

  has(header: string, matcher?: AxiosHeaderMatcher): boolean;

  delete(header: string | string[], matcher?: AxiosHeaderMatcher): boolean;

  clear(matcher?: AxiosHeaderMatcher): boolean;

  normalize(format: boolean): AxiosHeaders;

  concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;

  toJSON(asStrings?: boolean): RawAxiosHeaders;

  static from(thing?: AxiosHeaders | RawAxiosHeaders | string): AxiosHeaders;

  static accessor(header: string | string[]): AxiosHeaders;

  static concat(...targets: Array<AxiosHeaders | RawAxiosHeaders | string | undefined | null>): AxiosHeaders;

  setContentType(value: ContentType, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getContentType(parser?: RegExp): RegExpExecArray | null;
  getContentType(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasContentType(matcher?: AxiosHeaderMatcher): boolean;

  setContentLength(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getContentLength(parser?: RegExp): RegExpExecArray | null;
  getContentLength(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasContentLength(matcher?: AxiosHeaderMatcher): boolean;

  setAccept(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getAccept(parser?: RegExp): RegExpExecArray | null;
  getAccept(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasAccept(matcher?: AxiosHeaderMatcher): boolean;

  setUserAgent(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getUserAgent(parser?: RegExp): RegExpExecArray | null;
  getUserAgent(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasUserAgent(matcher?: AxiosHeaderMatcher): boolean;

  setContentEncoding(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getContentEncoding(parser?: RegExp): RegExpExecArray | null;
  getContentEncoding(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasContentEncoding(matcher?: AxiosHeaderMatcher): boolean;

  setAuthorization(value: AxiosHeaderValue, rewrite?: boolean | AxiosHeaderMatcher): AxiosHeaders;
  getAuthorization(parser?: RegExp): RegExpExecArray | null;
  getAuthorization(matcher?: AxiosHeaderMatcher): AxiosHeaderValue;
  hasAuthorization(matcher?: AxiosHeaderMatcher): boolean;

  [Symbol.iterator](): IterableIterator<[string, AxiosHeaderValue]>;
}

Above is the declaration, here is the implementation

class AxiosHeaders {
  constructor(headers) {
    headers && this.set(headers);
  }

  set(header, valueOrRewrite, rewrite) {
    const self = this;

    function setHeader(_value, _header, _rewrite) {
      const lHeader = normalizeHeader(_header);

      if (!lHeader) {
        throw new Error('header name must be a non-empty string');
      }

      const key = utils.findKey(self, lHeader);

      if(!key || self[key] === undefined || _rewrite === true || (_rewrite === undefined && self[key] !== false)) {
        self[key || _header] = normalizeValue(_value);
      }
    }

    const setHeaders = (headers, _rewrite) =>
      utils.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite));

    if (utils.isPlainObject(header) || header instanceof this.constructor) {
      setHeaders(header, valueOrRewrite)
    } else if(utils.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) {
      setHeaders(parseHeaders(header), valueOrRewrite);
    } else {
      header != null && setHeader(valueOrRewrite, header, rewrite);
    }

    return this;
  }

  get(header, parser) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils.findKey(this, header);

      if (key) {
        const value = this[key];

        if (!parser) {
          return value;
        }

        if (parser === true) {
          return parseTokens(value);
        }

        if (utils.isFunction(parser)) {
          return parser.call(this, value, key);
        }

        if (utils.isRegExp(parser)) {
          return parser.exec(value);
        }

        throw new TypeError('parser must be boolean|regexp|function');
      }
    }
  }

  has(header, matcher) {
    header = normalizeHeader(header);

    if (header) {
      const key = utils.findKey(this, header);

      return !!(key && this[key] !== undefined && (!matcher || matchHeaderValue(this, this[key], key, matcher)));
    }

    return false;
  }

  delete(header, matcher) {
    const self = this;
    let deleted = false;

    function deleteHeader(_header) {
      _header = normalizeHeader(_header);

      if (_header) {
        const key = utils.findKey(self, _header);

        if (key && (!matcher || matchHeaderValue(self, self[key], key, matcher))) {
          delete self[key];

          deleted = true;
        }
      }
    }

    if (utils.isArray(header)) {
      header.forEach(deleteHeader);
    } else {
      deleteHeader(header);
    }

    return deleted;
  }

  clear(matcher) {
    const keys = Object.keys(this);
    let i = keys.length;
    let deleted = false;

    while (i--) {
      const key = keys[i];
      if(!matcher || matchHeaderValue(this, this[key], key, matcher, true)) {
        delete this[key];
        deleted = true;
      }
    }

    return deleted;
  }

  normalize(format) {
    const self = this;
    const headers = {};

    utils.forEach(this, (value, header) => {
      const key = utils.findKey(headers, header);

      if (key) {
        self[key] = normalizeValue(value);
        delete self[header];
        return;
      }

      const normalized = format ? formatHeader(header) : String(header).trim();

      if (normalized !== header) {
        delete self[header];
      }

      self[normalized] = normalizeValue(value);

      headers[normalized] = true;
    });

    return this;
  }

  concat(...targets) {
    return this.constructor.concat(this, ...targets);
  }

  toJSON(asStrings) {
    const obj = Object.create(null);

    utils.forEach(this, (value, header) => {
      value != null && value !== false && (obj[header] = asStrings && utils.isArray(value) ? value.join(', ') : value);
    });

    return obj;
  }

  [Symbol.iterator]() {
    return Object.entries(this.toJSON())[Symbol.iterator]();
  }

  toString() {
    return Object.entries(this.toJSON()).map(([header, value]) => header + ': ' + value).join('\n');
  }

  get [Symbol.toStringTag]() {
    return 'AxiosHeaders';
  }

  static from(thing) {
    return thing instanceof this ? thing : new this(thing);
  }

  static concat(first, ...targets) {
    const computed = new this(first);

    targets.forEach((target) => computed.set(target));

    return computed;
  }

  static accessor(header) {
    const internals = this[$internals] = (this[$internals] = {
      accessors: {}
    });

    const accessors = internals.accessors;
    const prototype = this.prototype;

    function defineAccessor(_header) {
      const lHeader = normalizeHeader(_header);

      if (!accessors[lHeader]) {
        buildAccessors(prototype, _header);
        accessors[lHeader] = true;
      }
    }

    utils.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header);

    return this;
  }
}

So, if you want to add your own header name, you shouldn't write it like this

    config.headers = {
      ...config.headers,
      Authorization: `Bearer ${token.bearerToken}`,
    };

It should be like this

config.headers.set && config.headers.set('Authorization': `Bearer ${token.bearerToken}`)

@DigitalBrainJS DigitalBrainJS unpinned this issue Apr 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests