介绍
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
特性
- 从浏览器中创建 XMLHttpRequests
- 从 node.js 创建 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换 JSON 数据
客户端支持防御 XSRF
安装
使用 npm:
$ npm install axios
使用 bower:
$ bower install axios
使用 cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
案例
执行
GET请求// 为给定 ID 的 user 创建请求axios.get('/user?ID=12345').then(function (response) { //成功console.log(response);}).catch(function (error) { //失败console.log(error);});// 上面的请求也可以这样做axios.get('/user', {params: {ID: 12345}}).then(function (response) { //成功console.log(response);}).catch(function (error) { //失败console.log(error);});
执行
POST请求axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) { //成功console.log(response);}).catch(function (error) { //失败console.log(error);});
执行多个并发请求
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 API
axios(config)
GET// 获取远端图片axios({method:'get',url:'http://bit.ly/2mTM3nY',responseType:'stream'}).then(function(response) {response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});
POSTaxios({method: 'post',url: '/user/12345',data: {firstName: 'Fred',lastName: 'Flintstone'}});
axios(url[,config])
// 发送 GET 请求(默认的方法)axios('/user/12345');
