Skip to content

Instantly share code, notes, and snippets.

@mllrjb
Created December 5, 2016 18:10
Show Gist options
  • Save mllrjb/cb364390697e63a0a77e98d7355ce7e3 to your computer and use it in GitHub Desktop.
Save mllrjb/cb364390697e63a0a77e98d7355ce7e3 to your computer and use it in GitHub Desktop.
Piping Expressjs to another API via requestjs
'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