目前,前端发展飞速,前后端分离式开发已经不是新鲜事儿。
http://192.168.1.123/controller/action
,有人说上传代码到http://192.168.1.123/放在一个目录下不就行了,是啊!可以的。但是好麻烦有没有,调试接口需要传代码上去!!!!
1 2 3 4 |
$.post(<span class="hljs-string">'https://api.douban.com/v2/book/1220562'</span>,{},<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)</span>{ <span class="hljs-built_in">console</span>.log(data); }) |
所以,还是代理来的方便。
代理请求通俗点讲,就是把发往 a.com的请求,通过代理服务器发送到b.com。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<span class="hljs-comment">//服务端口</span> <span class="hljs-keyword">const</span> PORT=<span class="hljs-number">8000</span>; <span class="hljs-comment">//启动服务的根目录</span> <span class="hljs-keyword">const</span> server_root=<span class="hljs-string">'src'</span> <span class="hljs-comment">//引用gulp</span> <span class="hljs-keyword">var</span> gulp = <span class="hljs-built_in">require</span>(<span class="hljs-string">'gulp'</span>); <span class="hljs-comment">//引用gulp开启服务的插件</span> <span class="hljs-keyword">var</span> connect = <span class="hljs-built_in">require</span>(<span class="hljs-string">'gulp-connect'</span>); <span class="hljs-comment">//引用插件 gulp代理中间件插件</span> <span class="hljs-keyword">var</span> proxy = <span class="hljs-built_in">require</span>(<span class="hljs-string">'http-proxy-middleware'</span>); <span class="hljs-comment">//开启服务</span> gulp.task(<span class="hljs-string">'proxyServer'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>() </span>{ connect.server({ <span class="hljs-attr">root</span>: [server_root], <span class="hljs-attr">port</span>: PORT, <span class="hljs-attr">middleware</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">connect, opt</span>) </span>{ <span class="hljs-keyword">return</span> [ proxy(<span class="hljs-string">'/api'</span>, { <span class="hljs-attr">target</span>: <span class="hljs-string">'https://api.douban.com/v2'</span>,<span class="hljs-comment">//代理的目标地址</span> changeOrigin:<span class="hljs-literal">true</span>,<span class="hljs-comment">//</span> pathRewrite:{<span class="hljs-comment">//路径重写规则 </span> <span class="hljs-string">'^/api'</span>:<span class="hljs-string">''</span> } }) ] } }); }); |
说明
'/api' =>匹配你要代理的请求地址前缀
target=》你要把请求代理到哪
pathRewrite =》是把你再页面中写的请求地址 某部分 重写为后面的字符串
(例子中讲 请求中写的 /api
重写为 空字符串)
也就是发往 /api/book/1220562
的请求最终会被发往 https://api.douban.com/v2/book/1220562
页面写请求时的写法
1 2 3 4 |
$.post(<span class="hljs-string">'/api/book/1220562'</span>,{},<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">data</span>)</span>{ <span class="hljs-built_in">console</span>.log(data); }) |
当然还有其他的方式,比如 node、cros、jsonp、phpheader、nginx设置代理
作者:coder_turbo
链接:https://www.jianshu.com/p/cc543fd0d7c5
来源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。