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

為什么要反向代理?Nginx/Apache反向代理

直接進入正題:
1.下載http-proxy
cnpm install http-proxy --save-dev
2.在項目下面新建一個app.js文件,內(nèi)容如下:
 var http = require('http'), httpProxy = require('http-proxy');  
    
  // 新建一個代理 Proxy Server 對象  
  var proxy = 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.');  
 });  
     
 // 在每次請求中,調(diào)用 proxy.web(req, res config) 方法進行請求分發(fā)  
 var server =http.createServer(function(req, res) {  
   

      // 在這里可以自定義你的路由分發(fā)  
      var host = req.headers.host     
      switch(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);  

縮進敲的夠直觀了,且行且珍惜!

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

相關(guān)閱讀更多精彩內(nèi)容

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