Skip to content

TypeError: Failed to parse body as FormData with Axios #3676

@kettanaito

Description

@kettanaito

Bug Description

When performing a POST request with FormData and Axios, Undici fails to parse the request body.

Reproducible By

import axios from 'axios'
import { http } from 'msw'
import { setupServer } from 'msw/node'

const server = setupServer(
  http.post('*/upload', async ({ request }) => {
    // This is a regular Request instance constructed using Undici.
    const data = await request.formData()
    return Response.json(data)
  })
)
server.listen()

const request = axios.create({
  baseURL: 'https://example.com/upload',
  onUploadProgress() {},
})

const formData = new FormData()
const file = new Blob(['Hello', 'world'], { type: 'text/plain' })
formData.set('file', file, 'doc.txt')

const response = await request.post('https://example.com/upload', formData).catch(error => {
  throw error.response.data
})

This throws the following error:

{
  name: 'TypeError',
  message: 'Failed to parse body as FormData.',
  stack: 'TypeError: Failed to parse body as FormData.\n' +
    '    at node:internal/deps/undici/undici:5415:27\n' +
    '    at successSteps (node:internal/deps/undici/undici:5459:27)\n' +
    '    at fullyReadBody (node:internal/deps/undici/undici:4378:9)\n' +
    '    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)\n' +
    '    at async consumeBody (node:internal/deps/undici/undici:5468:7)\n' +
    '    at async file:///mswjs/msw/repro.mjs:8:18\n' +
    '    at async file:///mswjs/msw/lib/core/handlers/RequestHandler.mjs:121:24\n' +
    '    at async HttpHandler.run (file:///mswjs/msw/lib/core/handlers/RequestHandler.mjs:107:28)\n' +
    '    at async executeHandlers (file:///mswjs/msw/lib/core/utils/executeHandlers.mjs:10:14)\n' +
    '    at async until (file:///mswjs/msw/node_modules/.pnpm/@[email protected]/node_modules/@open-draft/until/lib/index.mjs:4:18)'
}

Node.js v22.3.0

I have a strong reason to believe something has changed in Undici between Node.js v21 and v22, which is causing this parsing issue. This same scenario is passing with the same dependencies using Node.js v18-v20.

Expected Behavior

Undici parses the FormData body sent from Axios.

Logs & Screenshots

Here's the FormData body read as text. This looks okay to me.

--axios-1.6.8-boundary-3Jx5-4T27f9Yo6Ul865QObiBm
Content-Disposition: form-data; name="file"; filename="doc.txt"
Content-Type: text/plain

Helloworld
--axios-1.6.8-boundary-3Jx5-4T27f9Yo6Ul865QObiBm--

Environment

  • Node v22.3.0
  • Axios v1.6.8 (the behavior is the same on the latest Axios version v1.7.7)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions