Gulp使用http-proxy-middleware插件解决跨域问题

前后端分离的开发,所面临的问题就是跨域问题,在原来gulp打包开发的基础上,增加代理转发功能,从而解决跨域问题。

跨域问题解决方式有很多种,这次主要使用Proxy代理的方式解决问题,Proxy的优势在于只需要前端进行代理,后端无需做任何处理,只需提供对应api接口即可。反正代理就是好用就行了。

查阅相关资料后可以使用http-proxy-middleware 模块进行代理,其官方说明文档也比较详细,我使用是gulp-connect作为web服务器,因此在此基础上,只需要增加对的代理中间件的相关配置即可,下面是我的Gulp配置

const { createProxyMiddleware } = require('http-proxy-middleware');  // 1.0.0版本的引用方式,不然会报错

function server() {
    $.connect.server({
        host: internalIp.v4.sync(),
        root: "./dist",
        port: '2222',
        index: false, // 默认不打开首页
        livereload: true,
       // debug: true 
        middleware: function (connect, opt) {
            return [
                createProxyMiddleware('/action', {
                    target: 'http://condor2400.startdedicated.com/action',//代理的目标地址
                    changeOrigin: true,//
                    pathRewrite: {//路径重写规则 
                        '^/action': ''
                    }
                })
            ]
        }
    });
}

上述配置将要访问的/action请求都转发到http://condor2400.startdedicated.com/中去。

http-proxy-middleware 相关配置

  1. 核心proxy中间件配置
const {createProxyMiddleware}= require('http-proxy-middleware');

var apiProxy = createProxyMiddleware('/api', {target: 'http://www.example.org'});
//                                   \____/   \_____________________________/
//                                     |                        |
//                                  需要转发的请求           目标服务器

// 'apiProxy' 现在已经准备作为一个中间件了。
  1. proxy中间件选项
    option.pathRewrite:对象/函数,重写目标url路径
// 重写
pathRewrite: {'^/old/api' : '/new/api'}   // 重写请求,比如我们源访问的是old/api,那么请求会被解析为/new/api
// 移除
pathRewrite: {'^/remove/api' : ''}
// 添加
pathRewrite: {'^/' : '/basepath/'}
// 自定义
pathRewrite: function (path, req) { return path.replace('/api', '/base/api') }

option.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';
} 

// 举例
 router: {
            // 如果请求主机 是 'dev.localhost:3000',则重写目标服务器为 'http://localhost:8000'
            'dev.localhost:3000' : 'http://localhost:8000'
        }
  1. http-proxy 事件
    参照 http-proxy events

你可能感兴趣的:(Gulp使用http-proxy-middleware插件解决跨域问题)