1.在Vue项目中config文件下的添加proxyTable配置
proxyTable:{
'/api': {
target:'',
changeOrigin:true,
pathRewrite: {
'^/api': ''
}
}
}
//api这个词可以任意换,但文下的词要一致
2.在Vue项目中config文件下的文件中配置BASE_API,即与上文对应的api
module.exports = merge(prodEnv, {
NODE_ENV: '"development"',
BASE_API: '"/api"'
})
//这里是开发模式下的配置,产品模式到中配置
3.在定义的axios文件中设置baseURL为配置好的.BASE_API
let http = axios.create({
baseURL: process.env.BASE_API,
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
},
timeout:5000,
})
4.在需要请求接口的组件中加入axios请求接口的代码,不需要在url的位置加/api路径,例如请求 /login 这个接口时,url直接写/login
// created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
created(){
axios.get('/login'
).then(function(res){
console.log(res.data);
}).catch(function (error) {
console.log(error);
});
}
若是使用原生的axios请求接口时发生了跨域,请看《Vue项目中proxyTable解决axios跨域问题》