为任意外部网址创建HTTPS代理

问题描述

我想使用Node.js(http-node-proxy)(对于我的情况是TypeScript)为请求任意网站的请求创建一个简单的代理。我知道关于这个困难的话题存在几个问题,但是到目前为止,没有一个问题对我有帮助。我尝试过:

import axios from 'axios';
import http from 'http';
import httpProxy from 'http-proxy';
import url from 'url';

async function mainHTTP() {
  // create the proxy
  const proxy = httpProxy.createProxy({});
  const server = http.createServer(function(request,response) {
    console.log([request.url,response.statusCode]);
    const requestURL = new url.URL(request.url!);
    const target = `${requestURL.protocol}//${requestURL.host}`;
    proxy.web(request,response,{target: target});
  });
  server.listen(8080);

  // make an example request
  const response = await axios.request({
    'url': 'http://www.example.org','proxy': {host: 'localhost',port: 8080},});
  console.log(response);
}
mainHTTP();

这很好用!,但仅适用于HTTP请求。所以我尝试了同样的事情“翻译”为HTTPS:

// ...
import fs from 'fs';
import https from 'https';

async function mainHTTPs() {
  // create the proxy
  const proxy = httpProxy.createProxy({});
  const ssl = { // keys tested,they work in other situations
    'key': fs.readFileSync('key.pem'),'cert': fs.readFileSync('cert.pem'),}
  const server = https.createServer(ssl,function(request,response.statusCode]); // error happens before this is executed!
    const requestURL = new url.URL(request.url!);
    const target = `${requestURL.protocol}//${requestURL.host}`;
    proxy.web(request,{target: target});
  });
  server.listen(8080);
  server.on('tlsClientError',(err) => console.log(err)); // added for debugging

  // make an example request
  const response = await axios.request({
    'url': 'https://www.example.org',});
  console.log(response);
}
mainHTTPs();

但是现在我突然收到“套接字挂断”错误。调试行给了我以下神秘错误

错误:9356:错误:1408F09C:SSL例程:ssl3_get_record:http请求:c:\ ws \ deps \ openssl \ openssl \ ssl \ record \ ssl3_record.c:322:”。

请注意,该错误发生在调用proxy.web之前,因此我认为它不应由代理本身引起。

有人能理解此错误,并且可以帮助我消除该错误吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)