gulp通过http-proxy-middleware开启反向代理,实现跨域

原理同nginx开启代理,只不过写法不同,所以直接上代码:

1、gulpfile.js配置代理服务器

gulp.task("domain3",function(){
    webServer.server({
        root:"./crossDomainC",
        port: 8082,
        livereload: true,
        middleware:function(connect,opt){
            return [
                proxy("/api",{
                    target:"https://api.douban.com/",
                    changeOrigin:true,
                    pathRewrite:{//路径重写规则 
                        '^/api':''
                    }
                })
            ]
        }
    });
})

2、服务器页面index.html

<!DOCTYPE html>
<html>
<head>
    <title>我是domain3</title>
</head>
<body>
    <p>我是domain3</p>
</body>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
     //请求本地js模拟后台数据
    $.ajax({
      type: "get",
      url: "/api/v2/movie/in_theaters",
      dataType: "dataType",
      success: function (res) {
        console.log(res)
      }
    });

    //请求本地js模拟后台数据
    $.ajax({
      type: "get",
      url: "/apis/index.js",
      dataType: "dataType",
      success: function (res) {
        console.log(res)
      }
    });
</script>
</html>

3、这里要注意的是,这只是粗浅的了解了下这个插件的功能,具体怎么用还得多多研究,所以这里暂时只找到了一种路由转发的方法。配置里的return按理来说可以写数组,具体怎么写还不清楚。有兴趣的朋友可以看看。

4、参考

  ①https://www.jianshu.com/p/a248b146c55a;

  ②https://blog.csdn.net/weixin_33712987/article/details/87071757

猜你喜欢

转载自www.cnblogs.com/helloNico/p/10688200.html