又是一个充满噱头的标题 = =。
思路是在研究 NodeJS
代理时想到的小 trick,说是 30 行,其实最重要的只有一行,即:
1
| req.pipe(request(URL)).res;
|
将客户端来的请求直接转发到相应的 URL 上,实现代理,基于这个原理,可以很容易的实现各种网站的镜像站点。
服务端代码加注释如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| const fs = require('fs'); const URL = require('url'); const http = require('http'); const request = require('request');
const port = 9901; const homeHTML = fs.readFileSync('./home.html', 'utf-8');
function requestInstance(url, ua) { return request({ url, headers: { 'User-Agent': ua } }) }
const Server = http.createServer((req, res) => { const url = URL.parse(req.url, true); if (url.pathname === '/') { res.writeHeader('200', { 'Contetn-Type': 'text/html' }); fs.createReadStream('./home.html').pipe(res); } else if (url.pathname === '/bg') { req.pipe(requestInstance(`https://bing.ioliu.cn/v1?${url.search}`, req.headers['user-agent'])).pipe(res); } else { req.pipe(requestInstance(`https://www.google.com/${url.path}`, req.headers['user-agent'])).pipe(res); } });
Server.listen(port, () => { console.log(`Server on port ${port}`); });
|
几行代码,完整可用的免翻墙 Google 搜索就完成了。
按这个思路来,任何网站都可以用这样的思路来玩耍,比如 po**hub.com
??