Created
July 18, 2015 08:34
-
-
Save rchampourlier/f2b4e0981f10edfafefb to your computer and use it in GitHub Desktop.
Minimal development proxy middleware for NodeJS. Usable to complete BrowserSync with a customized proxy.
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
// Basic development proxy middleware for NodeJS. | |
// | |
// You may use it with BrowserSync to proxy some paths | |
// to another service. Example of BrowserSync conig: | |
// | |
// browserSync({ | |
// server: { | |
// baseDir: 'dist', | |
// middleware: function(req, res, next) { | |
// proxy('/api/', 127.0.0.1', 9292, req, res, next); | |
// } | |
// } | |
// }); | |
var http = require('http'); | |
var proxy = function(path, host, port, req, res, next) { | |
var regex = new RegExp(path); | |
if (!req.url.match(regex)) { | |
console.log(req.url + ' doesn\'t match ' + path); | |
next(); | |
return; | |
} | |
var proxyRequest = function(req, res, next) { | |
console.log('proxy request ' + req.url + ' to ' + host + ':' + port + req.url); | |
var options = { | |
host: host, | |
port: port, | |
path: req.url, | |
headers: req.headers, | |
method: req.method | |
}; | |
callback = function(proxyRes) { | |
proxyRes.on('data', function(chunk) { | |
res.write(chunk); | |
}); | |
proxyRes.on('end', function () { | |
res.end(); | |
}); | |
}; | |
var proxyReq = http.request(options, callback); | |
req.on('data', function(chunk) { | |
proxyReq.write(chunk); | |
}); | |
req.on('end', function() { | |
proxyReq.end(); | |
}); | |
proxyReq.end(); | |
}; | |
proxyRequest(req, res, next); | |
}; | |
module.exports = proxy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment