Skip to content

Form-data resubmitting is broken #6240

@petrovmiroslav

Description

@petrovmiroslav

Describe the bug

Hello everyone. I've faced an issue. I hope someone could help me.

Here is a simple dummy code example:

const axiosInstance = axios.create({
  headers: {
    "Content-Type": "application/json;charset=utf-8",
  },
});

let retry = false;

axiosInstance.interceptors.response.use(undefined, (error) => {
  if (retry) return Promise.reject(error);
  retry = true;

  return axiosInstance.request(error.config);
});

axiosInstance.post("example.com/form", new FormData(), {
  headers: {
    "Content-Type": "multipart/form-data",
  },
});

xhrAdapder sets Content-Type to false, so that the browser can set it itself.

The first request gets a merged config:

{
  headers: {
    "Content-Type": false,
  },
  data: FormData {}
}

Inside the response interceptor error.config has the headers as an AxiosHeaders instance and looks like

{
  headers: AxiosHeaders {
    "Content-Type": false,
  },
  data: FormData {}
}

So when axios submits the request again:
headersToObject uses AxiosHeaders.prototype.toJSON, which removes all false values. Therefore mergeConfig returns a merged config which looks like

{
  headers: AxiosHeaders {
    "Content-Type": "application/json;charset=utf-8",
  },
  data: FormData {}
}

So dispatchRequest transforms the data to JSON string. And the request ends up with a config:

{
  headers: AxiosHeaders {
    "Content-Type": "application/json;charset=utf-8",
  },
  data: "{}"
}

But if the response interceptor looks like

axiosInstance.interceptors.response.use(undefined, (error) => {
  if (retry) return Promise.reject(error);
  retry = true;

  return axiosInstance.request({
    ...error.config,
    headers: { ...error.config.headers },
  });
});

everything works great.

Is it necessary that headersToObject uses AxiosHeaders.prototype.toJSON? Could it be switched to { ...thing }?

To Reproduce

sandbox

Code snippet

No response

Expected behavior

The "Content-Type" header shouldn't change and the data shouldn't be converted to string.

Axios Version

1.6.7

Adapter Version

No response

Browser

Chrome

Browser Version

119.0.6045.159

Node.js Version

No response

OS

OSX 14.2

Additional Library Versions

No response

Additional context/Screenshots

No response

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