node.js使用 http-proxy 創(chuàng)建代理服務(wù)器操作示例
本文實(shí)例講述了node.js使用 http-proxy 創(chuàng)建代理服務(wù)器操作。分享給大家供大家參考,具體如下:
代理,也稱網(wǎng)絡(luò)代理,是一種特殊網(wǎng)絡(luò)服務(wù),允許一個(gè)終端通過代理服務(wù)與另一個(gè)終端進(jìn)行非直接的連接,這樣利于安全和防止被攻擊。
代理服務(wù)器,就是代理網(wǎng)絡(luò)用戶去獲取網(wǎng)絡(luò)信息,就是信息的中轉(zhuǎn),負(fù)責(zé)轉(zhuǎn)發(fā)。
代理又分 正向代理 和 反向代理:
- 正向代理:幫助局域網(wǎng)內(nèi)的用戶訪問外面的服務(wù)。
- 反向代理:幫助外面的用戶訪問局域網(wǎng)內(nèi)部的服務(wù)。
一、安裝 http-proxy
npm install http-proxy --save
二、代理本地服務(wù)
const http = require('http'); const httpProxy = require('http-proxy'); //創(chuàng)建一個(gè)代理服務(wù) const proxy = httpProxy.createProxyServer(); //創(chuàng)建http服務(wù)器并監(jiān)聽8888端口 let server = http.createServer(function (req, res) { //將用戶的請(qǐng)求轉(zhuǎn)發(fā)到本地9999端口上 proxy.web(req, res, { target: 'http://localhost:9999' }); //監(jiān)聽代理服務(wù)錯(cuò)誤 proxy.on('error', function (err) { console.log(err); }); }); server.listen(8888, '0.0.0.0');
9999端口服務(wù)代碼:
const http = require('http'); http.createServer(function (req, res) { res.end('port : 9999'); }).listen(9999, '0.0.0.0');
當(dāng)們?cè)诒镜卦L問 8888 端口時(shí),proxy 會(huì)幫我們把請(qǐng)求代理到 9999 端口服務(wù),然后返回?cái)?shù)據(jù)。
二、通過host實(shí)現(xiàn)多個(gè)虛擬主機(jī),共用一個(gè)端口
const http = require('http'); const httpProxy = require('http-proxy'); //創(chuàng)建一個(gè)代理服務(wù) const proxy = httpProxy.createProxyServer(); //虛擬主機(jī) const hosts = { 'www.a.me': 'http://localhost:8888', 'www.b.me': 'http://localhost:9999', }; //創(chuàng)建http服務(wù)器并監(jiān)聽80端口 let server = http.createServer(function (req, res) { //獲取主機(jī)名 let host = req.headers['host']; host = host.split(':')[0]; //根據(jù)主機(jī)名,找到要代理的服務(wù) let target = hosts[host]; if (target) { proxy.web(req, res, { target: target }); proxy.on('error', function (err) { console.log(err); }); } else { res.end('end'); } }); server.listen(80, '0.0.0.0');
8888.js服務(wù)代碼:
const http = require('http'); http.createServer(function (req, res) { res.end('port : 8888'); }).listen(8888, '0.0.0.0');
9999.js服務(wù)代碼:
const http = require('http'); http.createServer(function (req, res) { res.end('port : 9999'); }).listen(9999, '0.0.0.0');
注意 www.a.me 和 www.b.me 這兩個(gè)域名需加入 C:\Windows\System32\drivers\etc\hosts 文件中。
127.0.0.1 www.a.me
127.0.0.1 www.b.me
當(dāng)我們?cè)L問 www.a.me 或 www.b.me 時(shí),就會(huì)自動(dòng)幫我們代理到指定端口的服務(wù)上去。
希望本文所述對(duì)大家node.js程序設(shè)計(jì)有所幫助。
相關(guān)文章
node.js中的fs.writeFileSync方法使用說明
這篇文章主要介紹了node.js中的fs.writeFileSync方法使用說明,本文介紹了fs.writeFileSync的方法說明、語法、接收參數(shù)、使用實(shí)例和實(shí)現(xiàn)源碼,需要的朋友可以參考下2014-12-12一文詳解Node中module.exports和exports區(qū)別
這篇文章主要介紹了一文詳解Node中module.exports和exports區(qū)別2023-03-03Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動(dòng)回收連接的方法示例
這篇文章主要介紹了Node.js實(shí)現(xiàn)mysql連接池使用事務(wù)自動(dòng)回收連接的方法,結(jié)合實(shí)例形式分析了node.js操作mysql連接池實(shí)現(xiàn)基于事務(wù)的連接回收操作相關(guān)技巧,需要的朋友可以參考下2018-02-02基于Node.js模板引擎教程-jade速學(xué)與實(shí)戰(zhàn)1
下面小編就為大家?guī)硪黄贜ode.js模板引擎教程-jade速學(xué)與實(shí)戰(zhàn)1。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09