node起本地服務器以及實現代理,前端接口轉發


上一篇文章寫了使用docker來做nginx鏡像實現本地的頁面代理以及接口轉發,但是需要下載docker,這個對於很多人來說還是顯得比較麻煩,於是這個文章就是介紹如何只用node就可以代理本地的頁面和接口轉發。

最簡單的方法就是

1.到 https://github.com/jiangzhenfei/server 下載,包括 proxy-conf.js 文件和 server.js 文件,復制到你需要代理的頁面的目錄,一般是index.html目錄,

2.配置 proxy-conf.js 文件:如下僅供參考

//代理配置
let conifg = {
    '/kdcos/':{   //將/kdcos/開頭的請求代理到http://172.24.4.220:80這台服務器(類似於vue的代理配置)
        target: 'http://172.24.4.220:80',
    },
    '/osm/':{     //將/osm/開頭的請求代理到http://120.79.90.199:80這台服務器
        target: 'http://120.79.90.199:80',
    }
}
module.exports = conifg  //導出配置文件

3.在當前目錄命令行輸入node server.js即可。

下面就是具體如何實現的,有興趣的可以看看。並不影響使用

 

1.首先我們介紹如何啟動服務器並且顯示本地的頁面

1.1如何起服務器(文件為index.js)

let http  = require('http')

let app = http.createServer ( function(request,response){
    let url = request.url
    if(request.url!=='/favicon.ico'){//清除第二次訪問
        response.end('hello world!')
    }
} ) 
app.listen(8000)

這個時候我們在當前的目錄命令行輸入 node  index.js,這個時候打開瀏覽器輸入localhost:8000,就可以在頁面看大hello world!.

1.2 基於上面的思路,我們可以通過文件讀取的方式將本地的index.html文件讀取然后傳入respones.end()

let http  = require('http')

let app = http.createServer ( function(request,response){
    let url = request.url
    if(request.url!=='/favicon.ico'){//清除第二次訪問//正常的讀取文件和其他資源加載
        fs.readFile( __dirname + ( url==='/' ? '/index.html':url ), function( err, data ){
            if( err ){
                console.log( 'file-err',err )
            }else{
                response.end( data )
            }
        });
    }
} ) 

當輸入localhost:8000或者localhost:8000/index.html也面就會出現當前所在目錄的index.html頁面,因為我們讀取了該頁面相應給該端口。

2.如何實現接口的轉發

以上我們實現啟動本地服務器展現頁面,但是頁面中的ajax接口如何實現轉發呢,比如我的url為/osm/client/sort的路由需要轉發到http://120.79.90.199:80這台服務器上,我們該如何實現呢

2.1使用http.request實現接口的轉發

var http = require('http')
var opt = {
   host:'這里放代理服務器的ip或者域名',
   port:'這里放代理服務器的端口號',
   method:'POST',//這里是發送的方法
   path:' https://www.google.com',     //這里是訪問的路徑
   headers:{
    //這里放期望發送出去的請求頭
   }
}
//以下是接受數據的代碼
var body = '';
var req = http.request(opt, function(res) {
    console.log("Got response: " + res.statusCode);
    res.on('data',function(d){
    body += d;
   }).on('end', function(){
      console.log(res.headers)
      console.log(body)
   });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
})
req.end();

2.2監聽頁面中的http請求,查看是否存在需要轉發的接口,利用上述方法轉發得到結果后返回前台(server.js)

let http  = require('http')
let fs = require('fs')

//哪些url請求需要代理(代理配置)
let conifg = {
    '/kdcos/':{//   /kdcos/開頭的url需要代理到http://172.24.4.220:80這台服務器
        target: 'http://172.24.4.220:80',
    },
    '/osm/':{
        target: 'http://120.79.90.199:80',
    }
}

let app = http.createServer ( function(request,response){
    let url = request.url
    if(request.url!=='/favicon.ico'){//清除第二次訪問
        //請求的數據是否存在代理
        for ( var key in conifg){
            if( url.indexOf(key) >-1 ){
                let info = conifg[key].target.split(':')
                let opt = {
                    protocol: info[0]+':',
                    host:    info[1].slice(2),
                    port:    info[2] || 80,
                    method:  request.method,//這里是發送的方法
                    path:    url,     //這里是訪問的路徑
                    json: true,
                    headers: request.headers
                }
                proxy( opt, response,request )//代理方法
                return;
            }
        }
        //正常的讀取文件和其他資源加載
        fs.readFile( __dirname + ( url==='/' ? '/index.html':url ), function( err, data ){
            if( err ){
                console.log( 'file-err',err )
            }else{
                console.log(data)
                response.end( data )
            }
        });
    }
} ) 

//代理轉發的方法
function proxy( opt,res ,req){
    var proxyRequest = http.request(opt, function(proxyResponse) { //代理請求獲取的數據再返回給本地res
        proxyResponse.on('data', function(chunk) {
            console.log( chunk.toString('utf-8') )
            res.write(chunk, 'binary');
        });
        //當代理請求不再收到新的數據,告知本地res數據寫入完畢。
        proxyResponse.on('end', function() {
            res.end();
        });
        res.writeHead(proxyResponse.statusCode, proxyResponse.headers);
    }); 
    //data只有當請求體數據進來時才會觸發
    //盡管沒有請求體數據進來,data還是要寫,否則不會觸發end事件
    req.on('data', function(chunk) {
        console.log('in request length:', chunk.length);
        proxyRequest.write(chunk, 'binary');
    });
    req.on('end', function() {
        //向proxy發送求情,這里end方法必須被調用才能發起代理請求
        //所有的客戶端請求都需要通過end來發起
        proxyRequest.end();
    }); 
}

app.listen(8000)
console.log('server is listen on 8000....')

現在我們在當前目錄命令行輸入 node server.js,瀏覽器打開localhost:8000就可以看到頁面。

2.3現在看看我們的index.html頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
</head>
<body>
    <h1>hahah</h1>
    <button class="button"> hahh </button>
    <button class="button2"> hahh </button>
    <script src="./a.js"></script>
    <script>
        $('.button').click( function(){
            $.ajax({
                url:'/kdcos/app/service?page=1&pageSize=5&name=',
                headers:{
                    "x-auth-token": "6491f900-a968-41b4-b56b-778eca4eb8b1",
                },
                success:function(e){
                }
            })
        } )
        $('.button2').click( function(){
            $.ajax({
                url:'/osm/client/sort',
                success:function(e){ 
                }
            })
        } )
    </script>
</body>
</html>

我們點擊頁面中的按鈕1和按鈕2,就可以看到不同的返回,來自兩台不同的服務器。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM