gulp通過http-proxy-middleware開啟反向代理,實現跨域
阿新 • • 發佈:2019-04-11
怎麽 ajax 數組 研究 rip eat 服務器 .ajax net
原理同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
gulp通過http-proxy-middleware開啟反向代理,實現跨域