axios

jQuery 时代,我们使用 ajax 向后台提交数据请求;Vue 时代,前后端数据的交互,推荐使用 Axios。


为什么官方推荐 axios,而不用 vue-resource 了?

vue-resource 是 Vue 官方 Ajax 库,在 Vue 1.x 的时候推荐使用;到了 Vue 2.x,官方觉得 Axios 已经比较成熟,没有必要再自己做一个,所以,vue-resource 便不再更新了。在 Vue 2.x 中,推荐使用 Axios。


[ 安装 ]  Axios 是基于 Promise 的 HTTP 库,可以在浏览器和 Nodejs 中使用。

// 使用 npm
    $ npm install axios --save

// 使用 cdn
    <script src="https://unpkg.com/axios@0.19.0/dist/axios.min.js"></script>

使用方式

在客户端使用:(1)在原来写 ajax 的位置使用(2)在 vue 中使用?!  &  在 node 中使用

// 可以通过 config 对象来配置 axios 请求

axios({
	method:'post',
	url:'./axios.php',
	data:{
		type:'top'
	}
})
.then(function(response){
	console.log(response);
})
.catch(function(err){
	console.log(err);
})

# 请求方法的别名:为了方便起见,为所有支持的方法提供了别名:

  • axios.request(config)            // 执行 request 请求
axios.request({config}) 
||
axios({
  url:''//请求地址
  method:'get' | 'post' //请求方式
  params:{} //请求参数

})
  • axios.get(url[, config])            // 执行 get 请求
// 方式1:为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 方式2:可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.post(url[, data[, config]])                 // 执行 post 请求
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

# 执行多个并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (data1, data2) {
    // 可以拿到两个请求的数据
    console.log(data1);
    console.log(data2);
  }));

# 自定义实例 axios.create([config])                          // 请求配置 & 配置的默认值?!

// 使用自定义配置新建一个axios实例

var instance = axios.create({
  // 请求配置
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

[ 实例方法 ] 指定的配置将与实例的配置合并,以下是可用的实例方法:

  • axios#request(config)
  • axios#get(url[, config])

// 响应结构?!使用 then 时,你将接收下面这样的响应:

axios.get('/user/12345')
  .then(function(response) {
    // 响应结构
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
  • axios#delete(url[, config])
  • axios#head(url[, config])
  • axios#post(url[, data[, config]])
  • axios#put(url[, data[, config]])
  • axios#patch(url[, data[, config]])

拦截器 interceptors

// 作用:在请求或响应被 thencatch 处理前拦截它们。


[1] 添加请求/响应拦截器

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });

如果想在稍后移除拦截器,可以这样:

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

[2] 为自定义 axios 实例,添加拦截器

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

错误处理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });