NodeJs搭建简单易用的本地代理服务器

node-proxy-server

引言

纯前端开发的时候,很多业务场景需要搭建本地服务器,方便页面浏览。
简单列举几个好处,比如

  • 局域网内多终端访问
  • 配合外网映射
  • 解决接口跨域问题

我常用到的几种本地搭建服务器的方式,比如

npm的serve package

  • 全局安装,serve ./启动,方便好用。
  • 直接启动的话不支持跨域。

webpack-dev-server

  • 一般使用在基于wepack的项目,普通H5搭建需要成本。
  • 支持跨域。

node-proxy-server 链接

  • 适用于普通页面开发,配置简单,node 命令启动。
  • 支持跨域。

node-proxy-server 原理

配置

配置接口地址的拦截,以及代理接口的地址。

let conifg = {
   
   
    '/xxxx1': {
   
    // 需要拦截的本地请求路径
        target: 'http://xxxxxxxx.com', // 代理地址
        port: 80, // 端口,默认80,某些地址可能是8080
    },
    '/xxxx2': {
   
    
        target: 'http://xxxxxxxx.com', 
        port: 80,
    }
    // ...other path
};

中间代理服务器

主要利用nodejs的 http 和 fs模块,创建一个中间服务器,接受页面请求,再通过中间服务器去请求真实接口,返回数据。

let http = require('http');
let fs = require('fs');
// 创建中间代理层http服务
let app = http.createServer(function (request, response) {
   
   });

拦截请求,转发请求

根据配置中的设定的拦截路径,拦截请求,并且转发到真实地址中。

// 判断是否存在代理地址
function hasProxy(url, request, response) {
   
   
    for (const key in conifg) {
   
    // 如果存在多个拦截路径
        const {
   
    target, port } = conifg[key];
        let info = target.split('//');
        let opts = {
   
    // 请求参数
            protocol: info[0],
            host: info[1],
            port: port || 80,
            method: request.method,
            path: url,
            json: true,
            headers: {
   
   }
        }
        proxy(opts, request, response);
        return true;
    }
    return false;
}

// 代理转发
function proxy(opts, request, response) {
   
   
    // 请求真实代理接口
    var proxyRequest = http.request(opts, function (proxyResponse) {
   
   
        // 代理接口返回数据,写入本地response
        proxyResponse.on('data', function (chunk) {
   
   
            response.write(chunk, 'binary');
        });
        // 代理接口结束,通知本地response结束
        proxyResponse.on('end', function () {
   
   
            response.end();
        });
        response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
    });

    // 本地接口数据传输,通知代理接口请求
    request.on('data', function (chunk) {
   
   
        proxyRequest.write(chunk, 'binary');
    });

    // 本地请求结束,通知代理接口请求结束
    request.on('end', function () {
   
   
        proxyRequest.end();
    });
}

普通资源请求

非拦截请求,直接通过。

// 普通请求和资源加载
fs.readFile(__dirname + url, function (err, data) {
   
   
    if (err) {
   
   
        console.log('请求失败', err);
    } else {
   
   
        response.end(data);
    }
});

源码

完整代码,欢迎自取。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章