Vue-CLI配置反向代理解决跨域
介绍
在前后分离的项目开发中,调用后端的接口时难免会遇到跨域。通过Vue-CLI配置反向代理可以解决跨域。
注:此方法只适用于本地开发。如发布到生产环境接口与前端在不同域,需服务器配置代理。
配置方法
打开项目中, config/index.js
在module.exports配置对象的dev属性中增加
proxyTable: {
'/master':{
target:"http://domain.com/",
changeOrigin:true,
pathRewrite:{
'^/master':'/master'
}
}
}完整修改如下图:

说明
'/master' 这个代理配置的名称
target : 后端接口的主机地址
changeOrigin : 是否开启代理
pathRewrite:{ '^/master1' : '/master2' } 其中 '^/master1'表示以/master1开始的接口,需要代理,并将其改写为/master。
完整示例
如真实后端接口为: http://www.domain.com/realApi/getData/
配置
proxyTable: {
'/api':{
target:"http://www.domain.com/",
changeOrigin:true,
pathRewrite:{
'^/localApi':'/realApi'
}
}
}2.请求接口URL,注意只写接口名,不要加域
const url =‘/localApi/getData';//不加域,并写localApi
const url = 'http://www.domain.com/realApi/getData/'//错误
或者不修改请求URL:
配置
proxyTable: {
'/realApi':{
target:"http://www.domain.com/",
changeOrigin:true,
pathRewrite:{
'^/realApi':'/realApi'
}
}
}2.请求接口URL,注意只写接口名,不要加域
const url =‘/realApi/getData';
2018-10-29 14:58:36
8420
0
参与讨论