如何解决设置一个非常简单的 Node.js 代理
我正在尝试使用 http-proxy
制作一个简单的 Node.js 代理。这是我的代码:
var http = require('http');
var httpProxy = require('http-proxy');
const url = require('url')
var proxy = httpProxy.createProxyServer({});
http.createServer(function(req,res) {
const query = require('querystring').parse(req.url.replace(/^\/(\?)?/,''));
const location = parseURL(query.url || req.url.slice(1));
if(!location){
res.end()
} else {
console.log(location)
proxy.web(req,res,{ target: location.href });
res.end()
}
// proxy.web(req,{ target: 'http://www.google.com/' });
}).listen(3000);
function parseURL(req_url) {
const match = req_url.match(/^(?:(https?:)?\/\/)?(([^\/?]+?)(?::(\d{0,5})(?=[\/?]|$))?)([\/?][\S\s]*|$)/i);
if (!match) {
return null;
}
if (!match[1]) {
// Scheme is omitted.
if (req_url.lastIndexOf('//',0) === -1) {
// "//" is omitted.
req_url = '//' + req_url;
}
// req_url = (match[4] === '443' ? 'http:' : 'http:') + req_url;
req_url = 'http://' + req_url;
}
return url.parse(req_url);
}
起初,我不明白为什么代理认为它代理了网站 /
,但我意识到 req.url 是 /
。我查看了其他人的做法,最后找到了 RobW 的 Cors-Anywhere,我从中获取了 parseURL()
。但是,这不起作用,并给我一个错误:
This site can’t provide a secure connection
localhost sent an invalid response.
这让我认为代理这个请求是重定向本地主机以尝试成为 https,比如 https://localhost
而不是 http。果然,我被重定向到 https://localhost
。我怎样才能阻止这种情况发生?有没有更好的方法来创建一个简单的代理?非常感谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。