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: 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` is the server URL that will be used for the request
url: '/user', // `method` is the request method to be used when making the request
method: 'get', // default // `baseURL` will be prepended to `url` unless `url` is absolute.
// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
// to methods of that instance.
baseURL: 'https://some-domain.com/api/', // `transformRequest` allows changes to the request data before it is sent to the server
// This is only applicable for request methods 'PUT', 'POST', and 'PATCH'
// The last function in the array must return a string or an ArrayBuffer
transformRequest: [function (data) {
// Do whatever you want to transform the data return data;
}], // `transformResponse` allows changes to the response data to be made before
// it is passed to then/catch
transformResponse: [function (data) {
// Do whatever you want to transform the data return data;
}], // `headers` are custom headers to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'}, // `params` are the URL parameters to be sent with the request
params: {
ID: 12345
}, // `paramsSerializer` is an optional function in charge of serializing `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` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
// When no `transformRequest` is set, must be a string, an ArrayBuffer or a hash
data: {
firstName: 'Fred'
}, // `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
timeout: 1000, // `withCredentials` indicates whether or not cross-site Access-Control requests
// should be made using credentials
withCredentials: false, // default // `adapter` allows custom handling of requests which makes testing easier.
// Call `resolve` or `reject` and supply a valid response (see [response docs](#response-api)).
adapter: function (resolve, reject, config) {
/* ... */
}, // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
// This will set an `Authorization` header, overwriting any existing
// `Authorization` custom headers you have set using `headers`.
auth: {
username: 'janedoe',
password: 's00pers3cret'
} // `responseType` indicates the type of data that the server will respond with
// options are 'arraybuffer', 'blob', 'document', 'json', 'text'
responseType: 'json', // default // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default // `progress` allows handling of progress events for 'POST' and 'PUT uploads'
// as well as 'GET' downloads
progress: function(progressEvent) {
// Do whatever you want with the native progress event
}
}

响应的数据结构

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

{
// `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` is the config that was provided to `axios` for the request
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';

自定义实例默认配置

// Set config defaults when creating the instance
var instance = axios.create({
baseURL: 'https://api.example.com'
}); // Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

配置的优先顺序

Config will be merged with an order of precedence. The order is library defaults found in lib/defaults.js, then defaults property of the instance, and finally config argument for the request. The latter will take precedence over the former. Here's an example.

// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
var instance = axios.create(); // Override timeout default for the library
// Now all requests will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500; // Override timeout for this request as it's known to take a long time
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 {
// The request was made, but the server responded with a status code
// that falls out of the range of 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 is heavily inspired by the $http service provided in Angular. Ultimately axios is an effort to provide a standalone $http-like service for use outside of Angular.

License

MIT

vue2.0之axios使用详解的更多相关文章

  1. Vue2.0学习——axios用法详解

    功能特性 在浏览器中发送 XMLHttpRequests 请求 在 node.js 中发送 http请求 支持 Promise API 拦截请求和响应 转换请求和响应数据 自动转换 JSON 数据 客 ...

  2. Vue2.0学习--Vue数据通信详解

    一.前言 组件是 vue.js最强大的功能之一,而组件实例的作用域是相互独立的,这就意味着不同组件之间的数据无法相互引用.组件间如何传递数据就显得至关重要.本文尽可能罗列出一些常见的数据传递方式,如p ...

  3. Hadoop2.2.0分布式安装配置详解[2/3]

    前言 本文主要通过对hadoop2.2.0集群配置的过程加以梳理,所有的步骤都是通过自己实际测试.文档的结构也是根据自己的实际情况而定,同时也会加入自己在实际过程遇到的问题.搭建环境过程不重要,重要点 ...

  4. Android 6.0 RK3288 ROM编译详解+命令详解【转】

    本文转载自:http://blog.csdn.net/MLQ8087/article/details/58607692 Android 6.0 RK3288 ROM编译详解+命令详解 原创 2017年 ...

  5. Spring3.0.5jar包用法详解 [转载]

    Spring3.X以后jar包进行了重构,取消了原来2.X版本中的总的spring.jar包,而是把总包中的功能全部分开打包.正在向osgi靠拢. 各个jar包详解如下: 1. org.springf ...

  6. Vue2+webpack+node 配置+入门+详解

    Vue2介绍 1.vue2.0 Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架. Vue 的核心库只关注视图层 采用单文件组件 复杂大型单页应用程序(SPA) 响 ...

  7. zabbix Server 4.0 监控JMX监控详解

    zabbix Server 4.0 监控JMX监控详解 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任.   大家都知道,zabbix server效率高是使用C语言编写的,有很多应用 ...

  8. hadoop2.2.0 centos 编译安装详解

    http://blog.csdn.net/w13770269691/article/details/16883663 废话不讲,直切正题. 搭建环境:Centos x 6.4 64bit 1.安装JD ...

  9. vue cli3.0快速搭建项目详解(强烈推荐)

    这篇文章主要介绍下vue-cli3.0项目搭建,项目结构和配置等整理一下,分享给大家. 一.介绍 Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统.有三个组件: CLI:@vue/cl ...

随机推荐

  1. kali linux源大全

    输入leafpad /etc/apt/sources.list进入        #官方源 deb http://http.kali.org/kali kali main non-free contr ...

  2. Powershell批量安装SNMP服务

    我要给node5-8的节点都安装snmp服务 如果不知道要安装的服务的名字,用get-windowsfeature 能显示出来所有的名字 Invoke-Command -ComputerName no ...

  3. Dockfile制作镜像

    讲一个简单的案例 @哈希码用来校验,这样子会安全 MAINTANIER可能将会被LABEL代替,仅仅说说明一下镜像信息罢了. 1.首先是我们创建一个镜像 [root@ELK-chaofeng08 ~] ...

  4. 数组实例的 copyWithin()

    用途:在当前数组内部,将指定位置的成员复制到其他位置(会覆盖原有成员),然后返回当前数组.也就是说,使用这个方法,会修改数组本身. 用法:Array.prototype.copyWithin(targ ...

  5. LeetCode算法题-Power Of Three(Java实现-七种解法)

    这是悦乐书的第204次更新,第215篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第71题(顺位题号是326).给定一个整数,写一个函数来确定它是否为3的幂.例如: 输入 ...

  6. LeetCode算法题-Minimum Depth of Binary Tree(Java实现)

    这是悦乐书的第168次更新,第170篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第27题(顺位题号是111).给定二叉树,找到它的最小深度.最小深度是沿从根节点到最近的 ...

  7. JSX格式化代码,你值得拥有!

    ext install prettier-vscode https://segmentfault.com/q/1010000014822745

  8. chrome postman插件手动安装

    注:转自 http://blog.csdn.net/u010246789/article/details/51481134 1.下载postman插件,可以自己到网上下载,也可以点击http://do ...

  9. postgresql + mybatis insert主键自增方法

    postgresql + mybatis插入记录时设置自增主键方法: 一.数据库设置主键自增 1.数据库中id字段选择serial4类型后,会在默认值中生成 nextval('app_id_seq': ...

  10. (2)Python索引和切片