Skip to content

Retry Handler Fails When Request Has a Body #3288

@sdelano

Description

@sdelano

Bug Description

When a body is provided to a request, such as in a PUT request, the retry handler fails with UND_ERR_REQ_CONTENT_LENGTH_MISMATCH.

Reproducible By

repro.ts:

import http from 'http';
import { Agent, RetryAgent } from 'undici';

const myDispatcher = new RetryAgent(new Agent());

async function failListener(req, res) {
  res.setHeader('content-type', 'application/json');
  res.writeHead(500);
  res.end(`{"message": "failure"}`);
}

async function makeRetryRequest() {
  const result = await fetch('http://localhost:3333/fail', {
    method: 'PUT',
    body: JSON.stringify({ foo: 'bar', baz: 'bat' }),
    headers: {
      'content-type': 'application/json',
    },
    dispatcher: myDispatcher,
  });
  console.log(result);
}

async function main() {
  http.createServer(failListener).listen(3333, makeRetryRequest);
}

main();
npx tsx repro.ts

Expected Behavior

The request should be retried and should not fail because undici fails to handle re-use of the body correctly.

Logs & Screenshots

> npx tsx repro.ts
node:internal/deps/undici/undici:11372
    Error.captureStackTrace(err, this);
          ^

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11372:11)
    at Server.makeRetryRequest REDACTED/repro.ts:13:18) {
  cause: RequestContentLengthMismatchError: Request body length does not match content-length header
      at AsyncWriter.end REDACTED/node_modules/undici/lib/dispatcher/client-h1.js:1319:15)
      at writeIterable (REDACTED/node_modules/undici/lib/dispatcher/client-h1.js:1201:12) {
    code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'
  }
}

Node.js v20.8.1

Environment

  • macOS 14.4.1
  • nodejs v20.8.1
  • undici 6.18.0

Additional context

None

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions