-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
69 lines (64 loc) · 2.03 KB
/
index.js
File metadata and controls
69 lines (64 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var httpProxy = require("http-proxy");
function ProxyFilter(server) {
var self = this;
var utils = self.utils = server.require("$./core/utils");
//读取配置
self.configs = server.configs.proxy || {};
self.configs.options = self.configs.options || {};
if (utils.isNull(self.configs.options.xfwd)) {
self.configs.options.xfwd = true;
}
if (utils.isNull(self.configs.options.changeOrigin)) {
self.configs.options.changeOrigin = true;
}
self.configs.rules = self.configs.rules || {};
//新建一个代理 Proxy Server 对象
self.proxy = httpProxy.createProxyServer(self.configs.options);
//proxy req
self.onProxyReqHandler = self.onProxyReqHandler.bind(self);
self.proxy.on("proxyReq", self.onProxyReqHandler);
};
ProxyFilter.prototype.onProxyReqHandler = function (proxyReq, req, res, options) {
var self = this;
if (!self.configs.headers) return;
var symbols = Object.getOwnPropertySymbols(proxyReq.connection);
var innerReq = proxyReq.connection[symbols[symbols.length - 1]];
self.utils.each(self.configs.headers, function (name, value) {
proxyReq.setHeader(name, value);
if (innerReq.headers) innerReq.headers[name] = value;
if (name === 'host') {
innerReq.host = value;
innerReq.hostname = value;
innerReq.servername = value;
}
});
};
ProxyFilter.prototype.matchRule = function (url) {
var self = this;
var rule = null;
self.utils.each(self.configs.rules, function (exprText, target) {
var expr = new RegExp(exprText);
if (expr.test(url)) {
var urlParts = expr.exec(url);
rule = {
url: urlParts.length > 1 ? urlParts[1] : url,
target: target
};
}
});
return rule;
};
ProxyFilter.prototype.onRequest = function (context, next) {
var self = this;
var res = context.res,
req = context.req;
//匹配规则表达式
var rule = self.matchRule(req.url);
if (!rule) return next();
req.url = rule.url || "/";
//代理请求
self.proxy.web(req, res, {
"target": rule.target
});
};
module.exports = ProxyFilter;