Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(fetch): connection is cancelled when redirecting #1787

Merged
merged 1 commit into from Nov 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion lib/fetch/index.js
Expand Up @@ -781,8 +781,11 @@ async function mainFetch (fetchParams, recursive = false) {
// https://fetch.spec.whatwg.org/#concept-scheme-fetch
// given a fetch params fetchParams
async function schemeFetch (fetchParams) {
// Note: since the connection is destroyed on redirect, which sets fetchParams to a
// cancelled state, we do not want this condition to trigger *unless* there have been
// no redirects. See https://github.com/nodejs/undici/issues/1776
// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
if (isCancelled(fetchParams)) {
if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) {
return makeAppropriateNetworkError(fetchParams)
}

Expand Down
2 changes: 1 addition & 1 deletion lib/fetch/response.js
Expand Up @@ -436,7 +436,7 @@ function makeAppropriateNetworkError (fetchParams) {
// otherwise return a network error.
return isAborted(fetchParams)
? makeNetworkError(new DOMException('The operation was aborted.', 'AbortError'))
: makeNetworkError(fetchParams.controller.terminated.reason)
: makeNetworkError('Request was cancelled.')
}

// https://whatpr.org/fetch/1392.html#initialize-a-response
Expand Down
29 changes: 29 additions & 0 deletions test/fetch/redirect.js
@@ -0,0 +1,29 @@
'use strict'

const { test } = require('tap')
const { createServer } = require('http')
const { once } = require('events')
const { fetch } = require('../..')

// https://github.com/nodejs/undici/issues/1776
test('Redirecting with a body does not cancel the current request - #1776', async (t) => {
const server = createServer((req, res) => {
if (req.url === '/redirect') {
res.statusCode = 301
res.setHeader('location', '/redirect/')
res.write('<a href="/redirect/">Moved Permanently</a>')
setTimeout(() => res.end(), 500)
return
}

res.write(req.url)
res.end()
}).listen(0)

t.teardown(server.close.bind(server))
await once(server, 'listening')

const resp = await fetch(`http://localhost:${server.address().port}/redirect`)
t.equal(await resp.text(), '/redirect/')
t.ok(resp.redirected)
})