axios的使用

1.安装命令:cnpm instal axios –save

2.main.js引入全局使用

1
2
3
4
//axios

import axios from 'axios'
Vue.prototype.$axios = axios

3.组件或页面中使用

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
 methods: 
      {
        testAxios1:function(){
            console.log('test');
             this.$axios({
                method: 'get',
                url: 'data/personData.json'
                })
                .then(function (response) {
                console.log(response)
                })
                .catch(function (error) {
                console.log(error)
                })
        },

axios配置开发环境跨域请求代理

1.配置BaseUrl

在main.js中,配置数据所在服务器的前缀(即固定部分),代码如下:

1
2
3
4
import axios from 'axios'
Vue.prototype.$axios = axios
axios.defaults.baseURL = '/api'  //关键代码
Vue.config.productionTip = false

2.打开config/index.js

在这里面找到proxyTable{},改为这样:

1
2
3
4
5
6
7
8
9
proxyTable: {
  '/api': {
    target:'http://api.douban.com/v2', // 你请求的第三方接口
    changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
    pathRewrite:{  // 路径重写,
      '^/api': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
    }
  }
},

3.使用

1
2
3
4
5
6
7
8
axios.get("/movie/top250").then((res) => {
  res = res.data
  if (res.errno === ERR_OK) {
     this.themeList=res.data;
  }
}).catch((error) => {
  console.warn(error)
})

==4.重新启动项目!!!==