webpack之proxyTable设置跨域

Vue项目在本地运行时,会存在跨域问题,报错如下:

解决办法:在config文件夹下的index.js中配置proxyTable.

proxyTable的作用

  • 简化请求的路径

当你在发起一个请求时,比如说你的访问路径是,http://abc.com/api/test,而且是在同域的情况下,可以在proxyTable中这么配置

1.请求资源路径在同一个项目路径api下,也就是你的请求路径中包含http://xxxx.com/api/xxxx,

    proxyTable: {
      '/api':{
        target:'http://abc.com',
        pathRewrite:{
          '^/api':'/api'
        },
      }
    },

2.发起请求的路径不包含/api,也就是说你的请求路径是这种形式,http://xxx.com/xxxx,而且是在同一个域名下。

    proxyTable: {
      '/api':{
        target:'http://abc.com',
        pathRewrite:{
          '^/api':''
        },
      }
    },
  • 解决跨域请求的问题

在解决跨域请求时,需要注意一个字段,changeOrigin,是否跨域,如果是跨域请求,设置成true,是一个boolean类型的数据。

跨域请求时,也存在两种情况接口中 接口路径中是否存在/api,如果不存在/api,在重写路径中用'',如果存在/api,则在pathRewrite中,配置成/api

如果访问的域名,不是一个,可以配置多个映射。

    proxyTable: {
      '/api':{
        target:'http://39.105.217.64:14667',//目标访问地址比如,域名或者ip+端口
        changeOrigin:true,//是否跨域
        pathRewrite:{
          '^/api':''
        },
      },
      '/test':{
        target:"http://f.apiplus.cn",
        changeOrigin:true,
        pathRewrite:{
          '^/test':'/test' //路径重写,如果重写了 访问路径会变成 http://f.apiplus.cn/test
        }
      },
      '/home':{
        target:'http://127.0.0.1:9091',//同域访问  不需要设置 changeOrigin
        pathRewrite:{
          '^/home':'/home'
        }
      }
    },

学习博客:

https://www.cnblogs.com/xiaoxiaossrs/p/8902535.html

https://www.cnblogs.com/ldlx-mars/p/7816316.html

https://blog.csdn.net/jikangjian/article/details/80798677

http://www.imooc.com/wenda/detail/454683

https://blog.csdn.net/qq_31965515/article/details/81251777

https://www.jianshu.com/p/95b2caf7e0da

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值