axios使用及介绍文档

安装

使用 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: 12345
    }
  })
  .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: 1000,
  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]])

请求配置

下面是可用的请求配置项,只有 url 是必需的。如果没有指定 method ,默认的请求方法是 GET

{
  // `url`是要用于请求的服务器URL
  url: '/user',

  // `method`是在发出请求时要使用的request方法
  method: 'get', // default

  // `baseURL'将被添加到`url`,除非url是绝对的。
  // 可以方便的将“baseURL”设置为一个axios实例,将相对URL传递给该实例的方法。
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest`允许在发送到服务器之前更改请求数据
  //  这只适用于请求方法'PUT','POST'和'PATCH'
  //  数组中的最后一个函数必须返回一个字符串或一个ArrayBuffer
  transformRequest: [function (data) {
    // 做任何你想转换的数据

    return data;
  }],

  // `transformResponse`可以在响应数据被传递给/ catch之前进行更改
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers`是要发送的自定义标题
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params`是与请求一起发送的URL参数
  params: {
    ID: 12345
  },

  // `paramsSerializer`是一个可选的函数,负责序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data`是作为请求体发送的数据,只适用于请求方法'PUT','POST'和'PATCH'
  //  当没有设置`transformRequest'时,必须是一个字符串,一个ArrayBuffer或一个哈希
  data: {
    firstName: 'Fred'
  },

  // `timeout`指定请求超时前的毫秒数。
  //如果请求比“timeout”长,请求将被中止。
  timeout: 1000,

  // `withCredentials`表示跨站点访问控制是否请求
  //应该使用凭据
  withCredentials: false, // default

  // `adapter`允许自定义处理请求,使测试更容易。
  //调用`resolve`或`reject`并提供一个有效的响应(参见[response docs](#response-api))。
  adapter: function (resolve, reject, config) {
    /* ... */
  },

  // `auth`表示应该使用HTTP Basic auth,并提供凭据。
  //这将设置一个“授权”头,覆盖任何现有的
  //使用`header`设置的`Authorization`自定义头文件。
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  }

  // `responseType`表示服务器响应的数据类型
  // options are 'arraybuffer', 'blob', 'document', 'json', 'text'
  responseType: 'json', // default

  // `xsrfCookieName`是用作xsrf令牌值的cookie的名称
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName`是携带xsrf令牌值的HTTP头的名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `progress` 可以处理'POST'和'PUT uploads'的进度事件
  //以及“GET”下载
  progress: function(progressEvent) {
    // 用本地进度事件做任何你想要的事情
  }
}

响应的数据结构

响应的数据包括下面的信息:

{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the headers that the server responded with
  headers: {},

  // `config`是提供给`axios`的请求的配置
  config: {}
}

当使用 then 或者 catch 时, 你会收到下面的响应:

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 默认配置

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

自定义实例默认配置

// 创建实例时设置配置默认值
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 修改实例后的默认值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

Config将与优先顺序合并。 该顺序是在lib / defaults.js中找到的库默认值,然后默认实例的属性,最后为该请求配置参数。 后者将优先于前者。 这是一个例子。

// 使用库提供的配置默认值创建一个实例
//此时,超时配置值为“0”,与库的默认值一样
var instance = axios.create();

// 库的超时超时默认值
//现在所有的请求将等待2.5秒才能超时
instance.defaults.timeout = 2500;

// 覆盖此请求的超时时间,因为它已知需要很长时间
instance.get('/longRequest', {
  timeout: 5000
}); 

拦截器

你可以在处理 then 或 catch 之前拦截请求和响应

// 添加一个请求拦截器
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// 添加一个响应拦截器
axios.interceptors.response.use(function (response) {
    // Do something with response data
    return response;
  }, function (error) {
    // Do something with response error
    return Promise.reject(error);
  });

移除一个拦截器:

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

你可以给一个自定义的 axios 实例添加拦截器:

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

错误处理

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

Promises

axios 依赖一个原生的 ES6 Promise 实现,如果你的浏览器环境不支持 ES6 Promises,你需要引入 polyfill

TypeScript

axios 包含一个 TypeScript 定义

/// <reference path="axios.d.ts" />
import * as axios from 'axios';
axios.get('/user?ID=12345');

Credits

axios受到Angular提供的$ http服务的极大启发。 最终的核心是努力提供一个独立的http类似服务,供Angular之外使用。

axios

转载于:https://my.oschina.net/mdu/blog/903191

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值