• 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,就可以看到不同的返回,来自两台不同的服务器。

  • 相关阅读:
    多线程
    文件上传案例及多线程版本
    TCP、UDP网络通信
    刷题:蘑菇街最小移动次数
    刷题:蘑菇街回文串
    刷题:蘑菇街
    Range Sum Query
    Submission Details
    Reverse Words in a String
    Counting Bits
  • 原文地址:https://www.cnblogs.com/zhenfei-jiang/p/9371450.html
Copyright © 2020-2023  润新知