vue配置本地代理解决跨域问题并配置不同环境改变target

我的vue搭建用的脚手架。

首先,在config下新建一个文件proxyConfig.js

module.exports = {
  proxy: {
    '/api': {
      target:'http://www.jinbi.com',  // 需要跨域的接口ip(域名)http://xxx
      changeOrigin:true,//是否跨域
      pathRewrite:{
        '/api': '/'
      }
    },
  }
}

然后在config下的index.js文件

const proxyConfig = require('./proxyConfig');

....

module.exports = {

  dev: {
       host:'我的本地ip',
      ...
      proxyTable:proxyConfig.proxy,
....

配置完后,重新运行一下。

请求改为如下:

原来:url:"http://www.jinbi.com/qryBusinessList?pageindex=1&pagecount=10"

现在:url:"/api/qryBusinessList?pageindex=1&pagecount=10"

 

然后查看network,请求的地址是:

http:// [我的本地ip] /api/qryBusinessList?pageindex=1&pagecount=10

而不是常见的:http:// [接口ip] /qryBusinessList?pageindex=1&pagecount=10

 

【这里顺便说一句,我这里手动设置了host为本地的ip:但这个是因为我的配置不设置运行有问题。】

 

然后是配置不同环境下的代理改变target;

需求:本地请求请求:http:// [我的本地ip] /api/qryBusinessList?pageindex=1&pagecount=10

           测试环境请求:http:// [测试ip] /api/qryBusinessList?pageindex=1&pagecount=10

           生产环境请求:http:// [生产ip] /api/qryBusinessList?pageindex=1&pagecount=10

 

配置如下:prod.env.js生产     test.env.js测试       dev.env.js本地

内容差不多:

module.exports里面配置
  
  API_HOST:'请求的接口ip'

 

然后proxyConfig.js

const proEnv=require('./prod.env');
const testEnv=require('./test.env');
const devEnv=require('./dev.env');

const env = process.env.NODE_ENV;
let target = '';
// 默认是本地环境
if(env==='production'){  // 生产环境
  target = proEnv.API_HOST;
}else if(env==='test'){ // 测试环境
  target = testEnv.API_HOST;
}else{  // 本地环境
  target = devEnv.API_HOST;
}

module.exports = {
  proxy: {
    '/api': {
      target:target,  // 接口域名
      changeOrigin:true,//是否跨域
      pathRewrite:{
        '/api': '/'
      }
    },
  }
}

以上全部

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值