在Node.js中使用https-proxy-agent没有响应

时间:2018-07-24 08:44:01

标签: node.js http proxy

我使用node-http-proxy npm创建了基本的代理服务器,我需要该服务器通过http代理运行(为此我正在使用https-proxy-agent),但是当我尝试执行HTTP请求时,却没有得到任何响应。而且我不知道它本身的服务器是否损坏(当手动尝试调用它时,它可以工作)或其他问题。

我的基本服务器:

const http = require('http');
const httpProxy = require('http-proxy');

const proxy = httpProxy.createProxyServer({});

const server = http.createServer(function(req, res) {
    proxy.web(req, res, { target: 'http://example.com' });
});

console.log("listening on port 5050")
server.listen(5050);  

Http请求:

let url = require('url');
let http = require('https');
let HttpsProxyAgent = require('https-proxy-agent');

let proxy = 'http://example:5050';

let endpoint = 'http://google.com';
let options = url.parse(endpoint);

let agent = new HttpsProxyAgent(proxy);
options.agent = agent;

http.get(options, res => {
    res.pipe(process.stdout);
});

***更新

如果有人发现自己陷入同一问题,这是我代理服务器的有效解决方案:

const http = require('http');
const net = require('net');
const url = require('url');

// Create an HTTP tunneling proxy
const proxy = http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {

    const srvUrl = url.parse(`http://${req.url}`);
    const srvSocket = net.connect({
        port: srvUrl.port,
        host: srvUrl.hostname,
    }, () => {
        cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
            'Proxy-agent: Node.js-Proxy\r\n' +
            '\r\n');

        srvSocket.write(head);
        srvSocket.pipe(cltSocket);
        cltSocket.pipe(srvSocket);
    });
});

proxy.listen(3000);

0 个答案:

没有答案