Skip to content

Commit 08772d9

Browse files
fix(fetch): decode response body when Location header is set on non-3xx response (nodejs#1628)
1 parent 89a340f commit 08772d9

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

lib/fetch/index.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1958,8 +1958,12 @@ async function httpNetworkFetch (
19581958

19591959
const decoders = []
19601960

1961+
const willFollow = request.redirect === 'follow' &&
1962+
location &&
1963+
redirectStatus.includes(status)
1964+
19611965
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding
1962-
if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !(request.redirect === 'follow' && location)) {
1966+
if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) {
19631967
for (const coding of codings) {
19641968
if (/(x-)?gzip/.test(coding)) {
19651969
decoders.push(zlib.createGunzip())

test/fetch/client-fetch.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,25 @@ test('do not decode redirect body', (t) => {
533533
})
534534
})
535535

536+
test('decode non-redirect body with location header', (t) => {
537+
t.plan(2)
538+
539+
const obj = { asd: true }
540+
const server = createServer((req, res) => {
541+
t.pass('response')
542+
res.statusCode = 201
543+
res.setHeader('location', '/resource/')
544+
res.setHeader('content-encoding', 'gzip')
545+
res.end(gzipSync(JSON.stringify(obj)))
546+
})
547+
t.teardown(server.close.bind(server))
548+
549+
server.listen(0, async () => {
550+
const body = await fetch(`http://localhost:${server.address().port}/resource`)
551+
t.strictSame(JSON.stringify(obj), await body.text())
552+
})
553+
})
554+
536555
test('Receiving non-Latin1 headers', async (t) => {
537556
const ContentDisposition = [
538557
'inline; filename=rock&roll.png',

0 commit comments

Comments
 (0)