使用nodejs做反向代理服務(wù)器

直接進(jìn)入正題:

1.下載http-proxy

cnpm install http-proxy --save-dev

2.在項(xiàng)目下面新建一個(gè)app.js文件,內(nèi)容如下:

varhttp =require('http'), httpProxy =require('http-proxy');// 新建一個(gè)代理 Proxy Server 對(duì)象? varproxy = httpProxy.createProxyServer({});// 捕獲異常? proxy.on('error',function(err, req, res){? ? ? ? ? res.writeHead(500, {'Content-Type':'text/plain'});? ? ? ? res.end('Something went wrong. And we are reporting a? ? ? ?

? ? ? custom error message.');? });// 在每次請(qǐng)求中,調(diào)用 proxy.web(req, res config) 方法進(jìn)行請(qǐng)求分發(fā)? varserver =http.createServer(function(req, res){// 在這里可以自定義你的路由分發(fā)? varhost = req.headers.hostswitch(host){case'www.veblen.com':? ? ? ? ? ? ? ? proxy.web(req, res, {target:'http://localhost:3000'});break;case'boy.veblen.com':? ? ? ? ? ? ? proxy.web(req, res, {target:'http://localhost:9527'});break;default:? ? ? ? ? ? ? res.writeHead(200, {'Content-Type':'text/plain'});? ? ? ? ? ? res.end('Welcome to my server!');? ? ? ? }? });console.log("listening on port 80")? server.listen(80);

縮進(jìn)敲的夠直觀了,且行且珍惜!

作者:vitor

鏈接:http://www.itdecent.cn/p/adec98717ef2

來(lái)源:簡(jiǎn)書(shū)

著作權(quán)歸作者所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容