怎么在node.js中利用http-proxy 創(chuàng)建一個(gè)代理服務(wù)器?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

代理又分 正向代理 和 反向代理:
正向代理:幫助局域網(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) {
//將用戶的請求轉(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)們在本地訪問 8888 端口時(shí),proxy 會(huì)幫我們把請求代理到 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
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。
分享文章:怎么在node.js中利用http-proxy創(chuàng)建一個(gè)代理服務(wù)器-創(chuàng)新互聯(lián)
URL地址:http://chinadenli.net/article14/cohpde.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、自適應(yīng)網(wǎng)站、網(wǎng)站排名、微信公眾號、動(dòng)態(tài)網(wǎng)站、靜態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容