Created
December 5, 2016 18:10
-
-
Save mllrjb/cb364390697e63a0a77e98d7355ce7e3 to your computer and use it in GitHub Desktop.
Piping Expressjs to another API via requestjs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const request = require('request'); | |
module.exports = function forward(req, res, next) { | |
var myRequest = request({ | |
url: req.url, | |
headers: req.headers | |
}); | |
req.pipe(myRequest) | |
.on('response', function (response) { | |
if (response.statusCode >= 400) { | |
var body = ''; | |
// chunks as strings, not buffers | |
response.setEncoding('utf8'); | |
response.on('data', function(chunk) { | |
body += chunk; | |
}); | |
response.on('end', function () { | |
if(body) { | |
next(new Error('error forwarding ' + JSON.stringify(body))); | |
} else { | |
next(new Error('error forwarding')); | |
} | |
}); | |
} else { | |
// does this work? I think so | |
myRequest.pipe(res); | |
} | |
}) | |
.on('error', function (err) { | |
next(err); | |
}); | |
} | |
return forward; | |
} | |
module.exports = forwardFactory; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment