天天看点

vue组件化挖矿之旅(五):axios的使用

axios

基于 Promise 的 HTTP 请求客户端,可同时在浏览器和 node.js 中使用

功能特性

在浏览器中发送 XMLHttpRequests 请求

在 node.js 中发送 http请求

支持 Promise API

拦截请求和响应

转换请求和响应数据

自动转换 JSON 数据

客户端支持保护安全免受 XSRF 攻击

安装

使用 bower:

bower install axios
           

使用 npm:

npm install axios
           

例子

发送一个 GET 请求

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });

// Optionally the request above could also be done as
axios.get('/user', {
    params: {
      ID: 
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });
           

发送一个 POST 请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (response) {
    console.log(response);
  });
           

发送多个并发请求

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) {
    // Both requests are now complete
  }));
           

axios API

可以通过给 axios传递对应的参数来定制请求:

axios(config)
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
axios(url[, config])
// Sned a GET request (default method)
axios('/user/12345');
           

请求方法别名

为方便起见,我们为所有支持的请求方法都提供了别名

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]])
           

注意

当使用别名方法时, url、 method 和 data 属性不需要在 config 参数里面指定。

并发

处理并发请求的帮助方法

axios.all(iterable)
axios.spread(callback)
           

创建一个实例

你可以用自定义配置创建一个新的 axios 实例。

axios.create([config])
var instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: ,
  headers: {'X-Custom-Header': 'foobar'}
});
           

实例方法

所有可用的实例方法都列在下面了,指定的配置将会和该实例的配置合并。

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]])
           

继续阅读