axios的使用

随着vue2.0的发布,停止对vue-resourse的维护,axios开始登上历史的舞台,这几天研究axios,特来与大家分享;

一、axios的使用方式

(1)通过cdn引入文档

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

2通过import引入

当然通过import引入首先要下载axios,而且由于axios不是vue插件,所以是不能用vue.use()的,方法如下

(2.1)下载axios

npm install axios -S
 
 (2.2)使用axios

import Axios from 'axios';
Vue.prototype.$http=Axios;

   ( 3 ) 使用方式

methods:{
	getDate:function(){
		this.$http({
			url:,
			method:'post/get',
			data:{
				//...
			}
		}).then(function(data){
			console.log(data)
		})
	}
}

二、axios请求api

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

三、axios基本的配置信息,比如请求头,baseURL,当然这里提供了一些比较方便配置项

{
  //请求的接口,在请求的时候,如axios.get(url,config);这里的url会覆盖掉config中的url
  url: '/user',

  // 请求方法同上
  method: 'get', // default
  // 基础url前缀
  baseURL: 'https://some-domain.com/api/',
  
    
  transformRequest: [function (data) {
    // 这里可以在发送请求之前对请求数据做处理,比如form-data格式化等,这里可以使用开头引入的Qs(这个模块在安装axios的时候就已经安装了,不需要另外安装)
  data = Qs.stringify({});
    return data;
  }],

  transformResponse: [function (data) {
    // 这里提前处理返回的数据

    return data;
  }],

  // 请求头信息
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  //parameter参数
  params: {
    ID: 12345
  },

  //post参数,使用axios.post(url,{},config);如果没有额外的也必须要用一个空对象,否则会报错
  data: {
    firstName: 'Fred'
  },

  //设置超时时间
  timeout: 1000,
  //返回数据类型
  responseType: 'json', // default

 
}

四、使用示例

(1)axios get请求

//通过给定的ID来发送请求
axios.get('/user?ID=12345')
  .then(function(response){
    console.log(response);
  })
  .catch(function(err){
    console.log(err);
  });
//以上请求也可以通过这种方式来发送
axios.get('/user',{
  params:{
    ID:12345
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(err){
  console.log(err);
});
(2)axios post请求
axios.post('/user',{
  firstName:'Fred',
  lastName:'Flintstone'
})
.then(function(res){
  console.log(res);
})
.catch(function(err){
  console.log(err);
});

(3)并发请求

function getUserAccount(){
  return axios.get('/user/12345');
}
function getUserPermissions(){
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(),getUserPermissions()])
  .then(axios.spread(function(acct,perms){
    //当这两个请求都完成的时候会触发这个函数,两个参数分别代表返回的结果
  }))




五、全局配置信息

axios.defaults.baseURL = 'http://api.exmple.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';












猜你喜欢

转载自blog.csdn.net/qq_25065257/article/details/74642352