我有以下代码动态代理网站到子域。
var app = require('express')();
var proxy = require('express-http-proxy');
var vhost = require('vhost');
app.get('/make', function (req, res) {
app.use(vhost('sub1.mysite.com', proxy("www.example.com");
res.send("Proxy Created");
});
app.get('/destroy', function (req, res) {
// Disable or Destroy the subdomain/proxy created above
// ???
});
app.listen(8080);
我如何从/destroy
路由禁用或销毁这个新创建的代理/子域?
app.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运行在express服务器
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;