gulp經過http-proxy-middleware開啓反向代理,實現跨域

原理同nginx開啓代理,只不過寫法不一樣,因此直接上代碼:javascript

一、gulpfile.js配置代理服務器html

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':'' } }) ] } }); })

二、服務器頁面index.htmljava

<!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>

三、這裏要注意的是,這只是粗淺的瞭解了下這個插件的功能,具體怎麼用還得多多研究,因此這裏暫時只找到了一種路由轉發的方法。配置裏的return按理來講能夠寫數組,具體怎麼寫還不清楚。有興趣的朋友能夠看看。jquery

四、參考nginx

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

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

相關文章
相關標籤/搜索