• gulp常用插件之http-proxy-middleware使用


    更多gulp常用插件使用请访问:gulp常用插件汇总


    http-proxy-middleware这是一个用于后台将请求转发给其它服务器。其实这并不是转给gulp使用的,在其它构建工具也可以用。

    更多使用文档请点击访问http-proxy-middleware工具官网

    例如:我们当前主机A为 http://localhost:3000/ , 现在浏览器发送一个请求,请求接口/api,这个请求的数据在另外一台服务器B上( http://www.example.org:4000 ) ,这时,就可通过在A主机设置代理,直接将请求发送给B主机。

    简单实现代码如下:

    var express = require('express');
    var proxy = require('http-proxy-middleware');
    
    var app = express();
    
    app.use('/api', proxy({target: 'http://www.example.org:4000', changeOrigin: true}));
    app.listen(3000);
    

    说明:我们利用express在3000端口启动了一个小型的服务器,利用了app.use('/api', proxy({target: 'http://www.example.org:4000/', changeOrigin: true}))这句话,使发到3000端口的/api请求转发到了4000端口。即请求http://localhost:3000/api 相当于请求 http://www.example.org:4000/api

    安装

    npm install --save-dev http-proxy-middleware
    

    用法和接口说明

    代理中间件配置。
    proxy([context,] config)

    • context:确定应将哪些请求代理到目标主机。(有关上下文匹配的更多信息)
    • options.target:要代理的目标主机。(协议+主机)
    
    var proxy = require('http-proxy-middleware');
     
    var apiProxy = proxy('/api', {target: 'http://www.example.org'});
             //                 \____/   \_____________________________/
             //                     |                    |
            //                需要转发的请求           目标服务器
    

    说明:第一个参数是可以省略的。

    下边示例是用Express构建的服务器中用法:

    // 引用依赖
    var express = require('express');
    var proxy = require('http-proxy-middleware');
    
    // proxy 中间件的选择项
    var options = {
            target: 'http://www.example.org', // 目标服务器 host
            changeOrigin: true,               // 默认false,是否需要改变原始主机头为目标URL
            ws: true,                         // 是否代理websockets
            pathRewrite: {
                '^/api/old-path' : '/api/new-path',     // 重写请求,比如我们源访问的是api/old-path,那么请求会被解析为/api/new-path
                '^/api/remove/path' : '/path'           // 同上
            },
            router: {
                // 如果请求主机 == 'dev.localhost:3000',
                // 重写目标服务器 'http://www.example.org' 为 'http://localhost:8000'
                'dev.localhost:3000' : 'http://localhost:8000'
            }
        };
    
    // 创建代理
    var exampleProxy = proxy(options);
    
    // 使用代理
    var app = express();
        app.use('/api', exampleProxy);
        app.listen(3000);
    

    参数一、[context]详解

    下边是一个完整地址划分:

    foo://example.com:8042/over/there?name=ferret#nose
     \_/  \_________________/\_________/ \_________/ \__/
      |           |            |            |       |
    协议          主机         路径          查询     碎片
    
    

    第一个参数主要设置要代理的路径,该参数具有如下用法:

    1)可以省略

    • proxy({...}):匹配任何路径,所有请求将被转发;

    2)可以设置为路径字符串

    • proxy('/', {...}) :匹配任何路径,所有请求将被转发;
    • proxy('/api', {...}):匹配/api开头的请求

    3)可以设置为数组

    • proxy(['/api', '/ajax', '/someotherpath'], {...}) :匹配多个路径

    4)可以设置为函数(自定义配置规则)

    /**
     * @return {Boolean}
     */
    var filter = function (pathname, req) {
        return (pathname.match('^/api') && req.method === 'GET');
    };
    
    var apiProxy = proxy(filter, {target: 'http://www.example.org'})
    

    5)可以设置为通配符

    细粒度的匹配可以使用通配符匹配,Glob 匹配模式由 micromatch创造,访问 micromatch or glob 查找更多用例。

    • proxy('**', {...}) 匹配任何路径,所有请求将被转发;
    • proxy('**/*.html', {...}) 匹配任何以.html结尾的请求;
    • proxy('/*.html', {...}) 匹配当前路径下以html结尾的请求;
    • proxy('/api/**/*.html', {...}) 匹配/api下以html为结尾的请求;
    • proxy(['/api/** ', '/ajax/**'], {...}) 组合
    • proxy(['/api/**', '!**/bad.json'], {...}) 不包括 **/bad.json 。

    参数二、config详解

    该接口是一个对象,里边包含的参数有如下:

    // proxy 中间件的选择项
    var config= {
            target: 'http://www.example.org', // 目标服务器 host
            changeOrigin: true,               // 默认false,是否需要改变原始主机头为目标URL
            ws: true,                         // 是否代理websockets
            pathRewrite: {
                '^/api/old-path' : '/api/new-path',     // 重写请求,比如我们源访问的是api/old-path,那么请求会被解析为/api/new-path
                '^/api/remove/path' : '/path'           // 同上
            },
            router: {
                // 如果请求主机 == 'dev.localhost:3000',
                // 重写目标服务器 'http://www.example.org' 为 'http://localhost:8000'
                'dev.localhost:3000' : 'http://localhost:8000'
            }
        };
    
    // 创建代理
    var exampleProxy = proxy(config);
    
    

    1)target

    用于设置目标服务器host。

    2)changeOrigin

    默认false,是否需要改变原始主机头为目标URL。

    **3)ws **

    设置是否代理websockets。

    4)pathRewrite

    重写目标url路径。

    // 重写
    pathRewrite: {'^/old/api' : '/new/api'}
    
    // 移除
    pathRewrite: {'^/remove/api' : ''}
    
    // 添加
    pathRewrite: {'^/' : '/basepath/'}
    
    // 自定义
    pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }
    

    5)router

    重写指定请求转发目标。

    // 使用主机或者路径进行匹配,返回最先匹配到结果
    // 所以配置的顺序很重要
    router: {
        'integration.localhost:3000' : 'http://localhost:8001',  // host only
        'staging.localhost:3000'     : 'http://localhost:8002',  // host only
        'localhost:3000/api'         : 'http://localhost:8003',  // host + path
        '/rest'                      : 'http://localhost:8004'   // path only
    }
    
    // 自定义
    router: function(req) {
        return 'http://localhost:8004';
    }
    

    事件

    http-proxy-middleware还提供了一些请求监听事件。

    • option.onError:
    // 监听proxy的onerr事件
    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.');
    });
    
    • option.onProxyRes:监听proxy的回应事件
    proxy.on('proxyRes', function (proxyRes, req, res) {
       console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, ));
    });
    
    • option.onProxyReq:监听proxy的请求事件
     proxy.on('proxyReq', function onProxyReq(proxyReq, req, res) {
         proxyReq.setHeader('x-added', 'foobar');
    });
    
    • option.onProxyReqWs:
    function onProxyReqWs(proxyReq, req, socket, options, head) {
         proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
    }
    
    • option.onOpen:监听来自目标服务器的信息
    proxy.on('open', function (proxySocket) {
       proxySocket.on('data', hybiParseAndLogMessage);
    });
    
    • option.onClose:展示websocket链接分离
    proxy.on('close', function (res, socket, head) {
       console.log('Client disconnected');
    });
    
  • 相关阅读:
    C#Light v0.007 又一次重大更新
    BeanFactory和FactoryBean
    java中四种引用类型
    JVM内存区域模型
    无锁算法CAS 概述
    线程安全性
    进程与线程的区别
    hadoop 错误处理机制
    hadoop 任务执行优化
    Hadoop的调度器总结
  • 原文地址:https://www.cnblogs.com/jiaoshou/p/12013517.html
Copyright © 2020-2023  润新知