Include websocket non-upgrade response

When the server do not accept the upgrade request for websockets the
server's response was previously not included and sent back. Now the
proxy will include the response in these cases. Fixes #890.
This commit is contained in:
Gustav Tiger 2017-06-20 13:38:28 +02:00 committed by Charlie Robbins
parent c9a556cfa5
commit bab02e909e
2 changed files with 23 additions and 18 deletions

View File

@ -77,6 +77,24 @@ module.exports = {
* @api private * @api private
*/ */
stream : function stream(req, socket, options, head, server, clb) { stream : function stream(req, socket, options, head, server, clb) {
var createHttpHeader = function(line, headers) {
return Object.keys(headers).reduce(function (head, key) {
var value = headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (var i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
}, [line])
.join('\r\n') + '\r\n\r\n';
}
common.setupSocket(socket); common.setupSocket(socket);
if (head && head.length) socket.unshift(head); if (head && head.length) socket.unshift(head);
@ -93,7 +111,10 @@ module.exports = {
proxyReq.on('error', onOutgoingError); proxyReq.on('error', onOutgoingError);
proxyReq.on('response', function (res) { proxyReq.on('response', function (res) {
// if upgrade event isn't going to happen, close the socket // if upgrade event isn't going to happen, close the socket
if (!res.upgrade) socket.end(); if (!res.upgrade) {
socket.write(createHttpHeader('HTTP/' + res.httpVersion + ' ' + res.statusCode + ' ' + res.statusMessage, res.headers));
res.pipe(socket);
}
}); });
proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) { proxyReq.on('upgrade', function(proxyRes, proxySocket, proxyHead) {
@ -119,22 +140,7 @@ module.exports = {
// Remark: Handle writing the headers to the socket when switching protocols // Remark: Handle writing the headers to the socket when switching protocols
// Also handles when a header is an array // Also handles when a header is an array
// //
socket.write( socket.write(createHttpHeader('HTTP/1.1 101 Switching Protocols', proxyRes.headers));
Object.keys(proxyRes.headers).reduce(function (head, key) {
var value = proxyRes.headers[key];
if (!Array.isArray(value)) {
head.push(key + ': ' + value);
return head;
}
for (var i = 0; i < value.length; i++) {
head.push(key + ': ' + value[i]);
}
return head;
}, ['HTTP/1.1 101 Switching Protocols'])
.join('\r\n') + '\r\n\r\n'
);
proxySocket.pipe(socket).pipe(proxySocket); proxySocket.pipe(socket).pipe(proxySocket);

View File

@ -415,7 +415,6 @@ describe('lib/http-proxy.js', function() {
client.on('error', function (err) { client.on('error', function (err) {
expect(err).to.be.an(Error); expect(err).to.be.an(Error);
expect(err.code).to.be('ECONNRESET');
proxyServer.close(); proxyServer.close();
done(); done();
}); });