1.在Vue项目中config文件下的index.js添加proxyTable的代码
dev: {
// 静态资源文件夹
assetsSubDirectory: 'static',
// 发布路径
assetsPublicPath: '/',
// 代理配置表,在这里可以配置特定的请求代理到对应的API接口
// 例如将'localhost:8080/api/xxx'代理到'http://xxxxxx.com/api/xxx'
proxyTable: {
'/api': {
target: 'http://xxxxxx.com', // 接口的域名
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
pathRewrite: {
'^/api': ''
}
}
},
2.在需要请求接口的组件中填写axios请求接口的代码,需要在url的位置加/api路径,例如请求 /login时,url需要写成 /api/login,此时 /api代表http://xxxxxx.com
// created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
created(){
axios.get('/api/login'
).then(function(res){
console.log(res.data);
}).catch(function (error) {
console.log(error);
});
}
注意: ‘/api’ 为匹配项,target 为被请求的地址,因为在 ajax 的 url 中加了前缀 ‘/api’,而原本的接口是没有这个前缀的,所以需要通过 pathRewrite 来重写地址,将前缀 ‘/api’ 转为 ‘/’。如果接口地址中就有 ‘/api’ 这种通用前缀(例如http://xxxxxx.com /api/login,),就可以把 pathRewrite 删掉或者写成 ‘^/api’: ‘/api’。
proxyTable: {
'/api': {
target: 'http://xxxxxx.com', // 接口的域名
// secure: false, // 如果是https接口,需要配置这个参数
changeOrigin: true, // 如果接口跨域,需要进行这个参数配置
pathRewrite: {
'^/api': '/api'
}
}
},
若是定义的axios的baseURL请求接口时发生了跨域,请看《Vue项目中proxyTable解决axios的baseURL跨域问题》