vue-cli3 proxy solves cross-domain issues

The principle of using proxy for cross-domain in Vue is to send the domain name to the local server (start the service of the Vue project, loclahost:8080), and then the local server requests the real server.

Configure the devServer.proxy object in the vue.config.js file (cli3 will automatically generate it, if not, create a new one in the root directory), where devServer.proxy points to a server API address in a development environment. The configuration is as follows:

module.exports = {
  lintOnSave: false, //关闭eslint检测\
  devServer:{
    open: false,//项目启动时是否自动打开浏览器,我这里设置为false,不打开,true表示打开
    proxy: {
      '/api': { 
        target: 'http://192.168.1.249:9527', //对应自己的接口,代理地址修改后必须重启项目
        changeOrigin: true, //是否允许跨域
        pathRewrite: {
          // 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/api/user/userInfo 时
          // 实际上访问的地址是:http://192.168.1.249:9527/user/userInfo,因为重写了 /api

          '^/api': ''
        }
      }
    }
  }
}
baseUrl configuration
//开发环境时,/api会被替换为上面配置的代理域名'http://192.168.1.249:9527'
//.env 默认全局配置文件
//.env.development 开发环境配置文件
//.env.production 生产环境配置文件
 //文件名为Vue的约定,不可随意更改
let config = process.env; //process是nodeJs的全局变量,其中包含了env的属性,Vue项目启动时会自动读取.env文件中的环境变量
//判断是否为开发环境,是,替换为'/api',否,替换为线上地址
let base = config.NODE_ENV === 'development' ? '/api' : '线上地址';

var http = {
  request:(url, method, data, headers, isjson)=>{
      return new Promise((resolve,reject)=>{
        let headerDefult = {
          "content-type": "application/x-www-form-urlencoded", //根据需要设置请求头
        }
        headers = merge(headerDefult, headers)
        data = isjson? data: qs.stringify(data)   //传入的数据是否为json格式
        axios({
          method, //请求方式
          baseURL:base, //域名
          url:url, //接口地址
          data, //数据
          timeout: 5000, //请求超时的时间,(超时后会进入catch)
          headers, //请求头
        })
        .then(res=>{
          if(res.status == 200){
            resolve(res.data)
          }else{
            reject( res && res.data || '')
          }
        })
        .catch(e=>{
          reject(e)
        })
      })
  }
}

Environment configuration

.env.production production environment

NODE_ENV = 'prod'
ENV = 'prod'
VUE_APP_BASE_API = 'https://www.xxxxx.com/api'

.env.test test environment

NODE_ENV = 'test'
ENV = 'test'
VUE_APP_BASE_API = 'http://www.xxxxxxx.com/api'

Configure the packaging command of package.json

//mode后面跟环境变量的值
"scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "build:prod":"vue-cli-service build --mode prod" //打包生产环境
    "build:test": "vue-cli-service build --mode test"  //打包测试环境
  },
Run the package command to package
测试环境:npm run build:test 
正式环境:npm run build:prod 

Guess you like

Origin blog.csdn.net/weixin_42215897/article/details/111697340