应用程序.js
var Ex = require('express');
var app = Ex();
app.listen(8080);
var DomainProxy = require('./DomainProxy').DomainProxy;
// Pass express instance 'app' into dp,
// dp will create a vhost router internally
var dp = new DomainProxy(app);
var proxies = [
{ domain: '1.local', site: 'http://www.bing.com' },
{ domain: '2.local', site: 'http://samanthagooden.com' },
{ domain: '3.local', site: 'http://www.courtleigh.com' },
{ domain: '4.local', site: 'http://example.com' }
];
dp.create(proxies);
app.get('/make', function (req, res) {
var subDomain = 'sub1.mysite.com';
var site = 'http://www.example.com'; // site need to contain 'http://', else dp link rewrite will not work correctly
dp.create([{domain:subDomain,site:site}]);
res.send("Proxy Created");
});
app.get('/destroy', function (req, res) {
var subDomain = 'sub1.mysite.com';
dp.destroy(subDomain);
res.send("Proxy Destroyed");
});
DomainProxy.js
我还结合了Nodejs 的答案 - BrowserSync running on express server
var proxy = require('express-http-proxy');
var url = require('url');
var vhost = require('vhost');
var Ex = require('express');
var DomainProxy = (function () {
function DomainProxy(app) { // DomainProxy
this.list = []; // vhost list array
this.router = Ex.Router();
app.use(this.router);
}
DomainProxy.prototype.create = function (proxies) {
proxies.forEach(p => {
// Destroy old proxy first
this.destroy(p.domain);
this.list.push(p.domain); // Add domain into list
this.router.use(vhost(p.domain, proxy(p.site, {
forwarDomainProxyath: (req, res) => url.parse(req.url).path,
intercept: (rsp, data, req, res, callback) => {
if (res._headers['content-type']) {
var contentType = res._headers['content-type'];
// console.log(contentType);
if (
contentType.indexOf('text') !== -1 ||
contentType.indexOf('javascript') !== -1
) {
// Rewrite links
var reg = new RegExp(p.site, 'g');
res.send(data.toString().replace(reg, ''));
} else {
res.send(data);
}
} else {
res.send(data);
}
}
})));
})
};
DomainProxy.prototype.destroy = function (domain) {
var i = this.list.indexOf(domain);
if (i !== -1) {
this.list.splice(i, 1);
this.router.stack.splice(i, 1);
}
};
return DomainProxy;
} ());
exports.DomainProxy = DomainProxy;