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前面加  api/;

得到的格式是:

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': '/'
      }
    },
  }
}

以上全部

猜你喜欢

转载自blog.csdn.net/github_38928905/article/details/85060821