1.NPM install axios 安装 axios, 在 main.JS 中引入并将 axios 改写为 vue 的属性
- import axios from 'axios'
- Vue.prototype.$axios = axios
- Vue.prototype.HOME='https://xxxx.xxx.com' // 发布正式或者测试版本不需要跨域, 直接调用 url 即可
- // Vue.prototype.HOME = '/api' // this.HOME 本地调试
2. 找到 config/index.JS 中的 proxyTable 配置代理来实现跨域请求
- proxyTable:{
- '/api':{
- target:"https://xxxx.xxx.com", // 接口域名
- changeOrigin:true,
- pathRewrite:{
- '^/api':""
- }
- }
- }
3. 在页面中 this.axios 调用即可
- // post
- this.$axios.post('/api/login',requestBody).then(res=>{
- console.log(res);
- },err=>{
- console.log(err);
- })
- // get
- let url = this.HOME + '/api/login'
- let data = this.$axios.get(url, {
- params: {
- name:name, // get 的参数写在 params 中
- pwd:pwd
- }
- })
来源: http://www.jianshu.com/p/2e68e9b6e209