Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Minimal development proxy middleware for NodeJS. Usable to complete BrowserSync with a customized proxy.
// 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