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(premature close) Redirect failing when response is chunked but empty #1222

Merged
Show file tree
Hide file tree
Changes from 1 commit
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
8 changes: 7 additions & 1 deletion src/index.js
Expand Up @@ -303,12 +303,18 @@ function fixResponseChunkedTransferBadEnding(request, errorCallback) {
properLastChunkReceived = Buffer.compare(buf.slice(-3), LAST_CHUNK) === 0;
});

socket.prependListener('close', () => {
const onSocketClose = () => {
if (!properLastChunkReceived) {
const error = new Error('Premature close');
error.code = 'ERR_STREAM_PREMATURE_CLOSE';
errorCallback(error);
}
};

socket.prependListener('close', onSocketClose);

request.on('abort', () => {
socket.removeListener('close', onSocketClose);
});
}
});
Expand Down
8 changes: 8 additions & 0 deletions test/main.js
Expand Up @@ -684,6 +684,14 @@ describe('node-fetch', () => {
});
});

it('should follow redirect after empty chunked transfer-encoding', () => {
const url = `${base}redirect/chunked`;
return fetch(url).then(res => {
expect(res.status).to.equal(200);
expect(res.ok).to.be.true;
});
});

it('should handle DNS-error response', () => {
const url = 'http://domain.invalid';
return expect(fetch(url)).to.eventually.be.rejected
Expand Down
8 changes: 8 additions & 0 deletions test/utils/server.js
Expand Up @@ -297,6 +297,14 @@ export default class TestServer {
res.socket.end('\r\n');
}

if (p === '/redirect/chunked') {
res.writeHead(301, {
Location: '/inspect',
'Transfer-Encoding': 'chunked'
});
setTimeout(() => res.end(), 10);
}

if (p === '/error/400') {
res.statusCode = 400;
res.setHeader('Content-Type', 'text/plain');
Expand Down