我正试图使一个代理服务器加载外部网站在我的域。我的目标是让人们访问myDomain.com/anyDomain.com,并能够使用anyDomain.com添加功能(注入JS)。
我尝试使用请求包来获取站点的html,然后将其发送到Express中的响应,但这种方法会使站点混乱(相对路径,缺少CSS,错误的JS请求等)。
是否存在完成此任务的节点包?如果没有,我自己怎么做呢?
谢谢!
这应该让你开始,它允许你调用fx http://localhost:6008/www.example.com/hello/world?foo=bar
,然后代理http://www.example.com/hello/world?foo=bar
,但如果你要代理其他网页,你会遇到各种各样的问题。
首先,它可能是不合法的。我不知道关于代理页面和修改它们的规则,你应该检查关于你的特定用例的法律。
其次,由于网页上的许多内容都使用绝对url(特别是如果内容使用多个域名,如CDN和api),这些资源仍然会指向原始目的地,这很可能会导致相当多的头痛
var express = require('express'),
http = require('http'),
url = require('url'),
app = express();
app.get('/:host*', function (request, response, next) {
var proxyurl = url.parse(request.url);
var path = request.params[0];
if (!!proxyurl.search) {
path += proxyurl.search;
}
http.get({
host: request.params.host,
path: path,
headers: {}
}, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
response.end(body);
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
});
app.listen(6008);
这可能是不合法的,所以免责声明:不要使用此代码。
下面是一个非常简单的例子,说明如何使用cookie来跟踪被代理主机的任何相对url。
基本上任何时候url路径匹配/*.com/*
,我们设置运行regex上,并设置一个cookie proxy_host
正好匹配*.com
。如果url路径与此不匹配,则检查cookie proxy_host
是否已设置。如果是,我们将url路径附加到cookie proxy_host
并代理该url。
var app = require('express')();
var request = require('request');
var cookieParser = require('cookie-parser');
var HOST_RE = /([^/]+.com)/;
app.use(cookieParser());
app.use(function(req, res) {
// Check if the url matches *.domain/www.somehost.com/*
if (HOST_RE.test(req.path)) {
// get a match for the host only, no paths
var proxyHost = HOST_RE.exec(req.path)[0];
// clean the path of the host, so that we can proxy the exact
// page the user requested
var path = req.path.replace(proxyHost, '');
// We have to cache the body in this instance because before we
// send the proxied response, we need to set our cookie `proxy_host`
var body = '';
return request.get('http://' + proxyHost + path)
.on('data', function(data) {
body += data;
})
.on('end', function() {
res.cookie('proxy_host', proxyHost);
res.end(body);
});
}
// Url does not match *.domain/www.somehost.com/*
// most likely a relative url. If we have the `proxy_host`
// cookie set, just proxy `http://` + proxy_host + `req.path`
if (req.cookies && req.cookies.proxy_host) {
return request.get('http://' + req.cookies.proxy_host + req.path).pipe(res);
}
// otherwise 404
res.status(404).end();
});
app.listen(8000);