Skip to content

Posting formdata may result in request header 'Content-Length': 'NaN' being set #5534

@thhermansen

Description

@thhermansen

Describe the bug

Passing a FormData object to Axios client may result in request header 'Content-Length': 'NaN' being set.

To Reproduce

Given the following code:

// client is an Axios instance
const pdf = await client.get(pdfUrl, { responseType: 'stream' });

const form = new FormData();
form.append('file', pdf.data, { filename, contentType: 'application/pdf' });

const res = await client.post(urlToUploadService, form);

We get the following request header added:

    headers: AxiosHeaders {
      Accept: 'application/json, text/plain, */*',
      'Content-Type': 'multipart/form-data; boundary=--------------------------852062351748726458865935',
      'User-Agent': 'axios/1.3.2',
      'Content-Length': 'NaN',
      'Accept-Encoding': 'gzip, compress, deflate, br'
    },

I believe 'Content-Length': 'NaN', is not something we want :) I'm pretty sure the header was not added with Axios version 1.2.6.


I believe this is related code:

axios/lib/adapters/http.js

Lines 266 to 267 in 0b44929

const knownLength = await util.promisify(data.getLength).call(data);
headers.setContentLength(knownLength);

If we log form's getLength:

  form.getLength((err, length) => {
    console.log(err, length);
  }),

We'll get a hint of what is going on:

null NaN

Axios Version

1.3.2

Adapter Version

No response

Browser

No response

Browser Version

No response

Node.js Version

v18.14.0

OS

macos 13.2

Additional Library Versions

No response

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