vue项目实现跨域:proxyTable

vue-cli生成的项目,可在config/index.js中配置proxyTable实现跨域。


proxyTable详解

    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:88',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api' // 重写路径
        }
      }
    },

以上,前端地址http://localhost:8088,后端地址http://localhost:88,对含有/api前缀的接口进行代理

  • '/api':匹配接口,并不是所有的请求都需要执行一下代理(如图片等)
  • target:目标请求地址
  • pathRewrite:重写路径,即匹配真实的后端接口(结合以下例子理解)

pathRewrite: {'^/api': '/api'},前端http://localhost:8088/api/imgList 匹配后端http://localhost:88/api/imgList

pathRewrite: {'^/api': ''},前端http://localhost:8088/api/imgList 匹配后端http://localhost:88/imgList

前端:

      axios({
        method: 'get',
        url:'api/imgList',
      }).then(function(res) {
        console.log(res)
      })

后端(django):

 path('api/imgList', views.View.as_view())
 # path('imgList', views.View.as_view())     当 pathRewrite: {'^/api': ''}

proxyTable实现原理

浏览器禁止跨域,服务端并不禁止跨域。

vue项目运行时,会配置启动一个node服务,浏览器的请求发送到这个服务器,该服务启动一个http代理,将请求转到设置的目标服务器。

vue的proxyTable用的是http-proxy-middleware

 

参考:https://segmentfault.com/q/1010000014042635

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值