Skip to content

Commit

Permalink
Remove "content-length: 0" from some requests, fixes cloudflare#193
Browse files Browse the repository at this point in the history
  • Loading branch information
Owen Smith committed Mar 8, 2022
1 parent b887877 commit 2db1ff7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
13 changes: 13 additions & 0 deletions packages/core/src/standards/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -700,6 +700,12 @@ const kDefaultHeadersToRemove = [
"user-agent",
];

const methodsExpectingPayload = [
"PUT",
"POST",
"PATCH"
];

class MiniflareDispatcher extends Dispatcher {
// dispatch, close & destroy are the only methods a Dispatcher must implement:
// https://github.com/nodejs/undici/blob/09059fb491b4158a25981eb5598262b43a18c6ae/lib/dispatcher.js
Expand Down Expand Up @@ -767,6 +773,13 @@ export async function fetch(
req.headers.delete("cf-connecting-ip");
// Add "MF-Loop" header for loop detection
req.headers.set(_kLoopHeader, String(ctx?.requestDepth ?? 1));
// Delete "content-length: 0" from bodyless requests. Some proxies add this,
// but undici considers it an error.
// See https://github.com/cloudflare/miniflare/issues/193

if (!methodsExpectingPayload.includes(req.method) && req.headers.get("content-length") === "0") {
req.headers.delete("content-length");
}

// Mark default headers for removal that aren't explicitly included
const removeHeaders: string[] = [];
Expand Down
17 changes: 17 additions & 0 deletions packages/core/test/standards/http.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,23 @@ test("fetch: removes Host and CF-Connecting-IP headers from Request", async (t)
"x-real-ip": "127.0.0.1",
});
});
test("fetch: removes Content-Length 0 from body-less requests", async (t) => {
// Should remove content-length: 0 from certain methods because undici sees it
// as an error: https://github.com/cloudflare/miniflare/issues/193
const upstream = (
await useServer(t, (req, res) => res.end(JSON.stringify(req.headers)))
).http;
const res = await fetch(upstream, {
method: "DELETE",
headers: {
"Content-Length": "0"
},
});
const headers = await res.json();
t.like(headers, {
host: upstream.host,
});
});
test("fetch: removes default fetch headers from Request unless explicitly added", async (t) => {
// Should remove accept, accept-language, sec-fetch-mode, and user-agent
// headers unless explicitly added: https://github.com/cloudflare/miniflare/issues/139
Expand Down

0 comments on commit 2db1ff7

Please sign in to comment.