Skip to content

Commit

Permalink
Fix redirect failing when response is chunked but empty. #1220 #1064
Browse files Browse the repository at this point in the history
  • Loading branch information
tekwiz committed Jul 26, 2021
1 parent b50fbc1 commit 186138a
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
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
16 changes: 16 additions & 0 deletions test/main.js
Expand Up @@ -684,6 +684,22 @@ describe('node-fetch', () => {
});
});

it('should handle https://blog.logrocket.com/feed', () => {
const url = 'https://blog.logrocket.com/feed';
return fetch(url).then(res => {
expect(res.status).to.equal(200);
expect(res.ok).to.be.true;
});
});

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

0 comments on commit 186138a

Please sign in to comment.