Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion lib/web/fetch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1322,7 +1322,11 @@ function httpRedirectFetch (fetchParams, response) {
// value of safely extracting request’s body’s source.
if (request.body != null) {
assert(request.body.source != null)
request.body = safelyExtractBody(request.body.source)[0]
const [body, contentType] = safelyExtractBody(request.body.source)
request.body = body
if (contentType) {
request.headersList.set('content-type', contentType, true)
}
}

// 15. Let timingInfo be fetchParams’s timing info.
Expand Down
46 changes: 45 additions & 1 deletion test/fetch/redirect.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const { test } = require('node:test')
const { createServer } = require('node:http')
const { once } = require('node:events')
const { fetch } = require('../..')
const { fetch, FormData } = require('../..')
const { closeServerAsPromise } = require('../utils/node-http')

// https://github.com/nodejs/undici/issues/1776
Expand Down Expand Up @@ -75,3 +75,47 @@ test('Redirecting with a body does not fail to write body - #2543', async (t) =>
t.assert.strictEqual(await resp.text(), 'ok')
t.assert.ok(resp.redirected)
})

// https://github.com/nodejs/undici/issues/4065
test('Redirecting with FormData updates Content-Type header boundary - #4065', async (t) => {
const server = createServer({ joinDuplicateHeaders: true }, (req, res) => {
if (req.url === '/redirect') {
res.writeHead(307, { location: '/target' })
res.end()
return
}

// Collect the request body and verify Content-Type boundary matches body boundary
const contentType = req.headers['content-type']
const boundaryMatch = contentType?.match(/boundary=(.+)$/)
const headerBoundary = boundaryMatch?.[1]

let body = ''
req.on('data', (chunk) => { body += chunk.toString() })
req.on('end', () => {
// Extract boundary from the body (first line is --boundary)
const bodyBoundaryMatch = body.match(/^--(.+)\r\n/)
const bodyBoundary = bodyBoundaryMatch?.[1]

// The header boundary must match the body boundary
t.assert.ok(headerBoundary, 'Content-Type header should have boundary')
t.assert.ok(bodyBoundary, 'Body should have boundary')
t.assert.strictEqual(headerBoundary, bodyBoundary, 'Content-Type boundary must match body boundary')

res.end('ok')
})
}).listen(0)

t.after(closeServerAsPromise(server))
await once(server, 'listening')

const formData = new FormData()
formData.append('field', 'value')

const resp = await fetch(`http://localhost:${server.address().port}/redirect`, {
method: 'POST',
body: formData
})
t.assert.strictEqual(await resp.text(), 'ok')
t.assert.ok(resp.redirected)
})