vue 配置代理

如果接口请求存在跨域问题且后端暂没时间解决,可以通过vue-cli配置代理的方式解决:

  1. .env.development中设置VUE_APP_BASE_API = Local Local为该项目运行时的服务器地址,
  2. vue.config.js中设置devServer:{proxy:'接口地址的公共部分'}
请求方法:request.get('/module/getInfo')  request为封装的axios,baseUrl=VUE_APP_BASE_API

接口请求地址:http://testapi.com/api/module/getInfo

正常情况下:VUE_APP_BASE_API = http://testapi.com/api

但由于该请求后端没解决跨域问题,所以通过代理改写为
//方式一
VUE_APP_BASE_API = http://localhost:8080     //http://localhost:8080为本项目跑起来的访问地址
devServer:{
  proxy:'http://testapi.com/api'          //通过改行代码,发送的请求 http://localhost:8080/module/getInfo转换成 http://testapi.com/api/module/getInfo
}
//方式二
VUE_APP_BASE_API = http://localhost:8080     //http://localhost:8080为本项目跑起来的访问地址
devServer:{
  proxy:{                                //该方式,可以配置多个代理服务器,对某些请求使用代理,使用该方式,确保 VUE_APP_BASE_API = http://localhost:8080 该值的端口号后无紧跟内容    
    '/module/getInfo':{                             //对请求 http://localhost:8080/module/getInfo 端口号后紧跟/module/getInfo 的请求 使用代理
        target: 'http://testapi.com',
        changeOrigin: true,
        pathRewrite: {
          '^/module/getInfo': '/api/module/getInfo'
        }
      }
  }
}

posted @ 2023-01-06 12:35  亦茫茫  阅读(1035)  评论(0编辑  收藏  举报