重要
如果你想使用HTTP連接到代理,請看到這一點,你需要使用連接方法
const options = {
port: 8080,
hostname: '10.7.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
socket.write('GET/HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end',() => {
proxy.close();
}
附加信息(不需要)
以下是關於如何創建代理併發出請求的完整代碼,我已經找到here。它基本上是創建一個服務器並通過它提出請求。
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) => {
// connect to an origin server
const srvUrl = url.parse(`http://${req.url}`);
const srvSocket = net.connect(srvUrl.port, 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);
});
});
// now that proxy is running
proxy.listen(1337, '127.0.0.1',() => {
// make a request to a tunneling proxy
const options = {
port: 1337,
hostname: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
const req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// make a request over an HTTP tunnel
socket.write('GET/HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end',() => {
proxy.close();
});
});
});
它創建通過http.createServer()
一個服務器,然後開始與proxy.listen()
聽他們這樣做之後,它連接使用HTTP的connect
方法,並在插座一個簡單的GET請求寫道,並將其發送給谷歌,因爲它是指定的路徑。
請看更新,並讓我知道它的工作原理:) @Daksh – turmuka