axios安装与使用:
-
npm安装
npm install axios
-
main.js文件中注册
import Axios from "axios"; //axios 用Vue.use(axios)会出现诡异的bug Vue.prototype.$axios=Axios
-
页面使用
this.$axios.get("https:xjxqgzh.cn/user/id") .then(res => { console.log(res) });
跨域:
域名 协议 ip地址 端口 任何一个不一样 就跨域
详解可见:博文地址
proxy代理:
vue-cli官方文档
在项目根目录下创建vue.config.js文件,代码如下
module.exports={
devServer:{
proxy: {
'/api': { //匹配请求路径,将'api'替换成target的地址
target: 'https:xjxqgzh.cn', //服务端地址
ws: true,
changeOrigin: true, // 允许跨域
pathRewrite:{
'^/api':''
}
},
'/oilprice': {
target: 'http://apis.juhe.cn', //服务端地址
ws: true,
changeOrigin: true, // 允许跨域
pathRewrite:{
'^/oilprice':''
}
},
}
},
}
页面请求
this.$axios.get("https:xjxqgzh.cn/user/id")
| |
改为
| |
V V
this.$axios.get("/api/user/id")
//页面实际请求地址:"https:xjxqgzh.cn/user/id"