Skip to content

Config header types are wrong in Axios.create #4184

@felixmosh

Description

@felixmosh

Describe the bug

The type of headers field in Axios.create config doesn't supports headers for specific requests method.

To Reproduce

Axios.create({
      baseURL: '/api',
      headers: {
        get: {
          'Cache-Control': 'no-cache',
          Pragma: 'no-cache',
          Accept: '*/*',
          'Accept-Encoding': 'gzip, deflate, br', 
        } , // this get field can't be an object
        'User-Agent': `${process.env.API_SERVER_NAME}/${process.env.BUILD_VERSION}`,
      },
    })

image

The js code do supports it.

axios/lib/defaults.js

Lines 126 to 132 in 1025d12

utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
defaults.headers[method] = {};
});
utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
});

Expected behavior

It should allow pass any request method inside headers

Environment

  • Axios Version [e.g. 0.23.0]
  • XHR/HTTP [e.g. XHR/HTTP]
  • Node.js Version [e.g. 13.0.1]
  • OS: [e.g. iOS 12.1.0, OSX 10.13.4]

Possible solution

it is possible to extend the AxiosRequestConfig type and use it in create method.

export interface AxiosCreateConfig extends Omit<AxiosRequestConfig, 'headers'> {
  headers: AxiosRequestHeaders | Partial<{
    delete: AxiosRequestHeaders,
    get: AxiosRequestHeaders,
    head: AxiosRequestHeaders,
    post: AxiosRequestHeaders,
    put: AxiosRequestHeaders,
    patch: AxiosRequestHeaders,
  }>;
}

export interface AxiosStatic extends AxiosInstance {
   create(config?: AxiosCreateConfig): AxiosInstance;
   Cancel: CancelStatic;
   CancelToken: CancelTokenStatic;
   Axios: typeof Axios;
}

Additional context/Screenshots

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions