Advertisement
Guest User

Untitled

a guest
Dec 5th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. 'use strict';
  2.  
  3. const request = require('request');
  4.  
  5. module.exports = function forward(req, res, next) {
  6. var myRequest = request({
  7. url: req.url,
  8. headers: req.headers
  9. });
  10. req.pipe(myRequest)
  11. .on('response', function (response) {
  12. if (response.statusCode >= 400) {
  13. var body = '';
  14. // chunks as strings, not buffers
  15. response.setEncoding('utf8');
  16. response.on('data', function(chunk) {
  17. body += chunk;
  18. });
  19. response.on('end', function () {
  20. if(body) {
  21. next(new Error('error forwarding ' + JSON.stringify(body)));
  22. } else {
  23. next(new Error('error forwarding'));
  24. }
  25. });
  26. } else {
  27. // does this work? I think so
  28. myRequest.pipe(res);
  29. }
  30. })
  31. .on('error', function (err) {
  32. next(err);
  33. });
  34. }
  35.  
  36. return forward;
  37. }
  38.  
  39. module.exports = forwardFactory;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement