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

本文介绍如何使用Gulp配置代理服务器,实现跨域请求。通过gulpfile.js文件设置,可将请求转发至目标服务器,如Douban API。代码示例展示了如何使用proxy中间件进行路径重写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理同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.youkuaiyun.com/weixin_33712987/article/details/87071757

转载于:https://www.cnblogs.com/helloNico/p/10688200.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值