axios

axios 是一个基于 Promise 的 HTTP 客户端,专门为浏览器和 node.js 服务

Vue 2.0 官方推荐使用 axios 来代替原来的 Vue request,所以这里介绍一下 axios 的功能和基本的使用方法,希望能够对各位所有帮助。^_^

功能

  • 在浏览器中发送 XMLHttpRequests 请求
  • 在 node.js 中发送 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换 JSON 数据格式
  • 客户端支持防范 XSRF 攻击

浏览器支持

axios 能够支持 IE7 以上的 IE 版本,同时能够支持大部分主流的浏览器,需要注意的是,你的浏览器需要支持 Promise,才能够使用 axios。所以比较好的做法是先安装 polyfill,然后再使用 axios。

安装

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

这里以 Vue 为例:在 NPM 中安装 axios 之后,需要在 main.js 文件中引用 package

import axios from 'axios'

然后全局绑定

Vue.prototype.$http = axios

然后可以在 .vue 文件中使用 $http 来代替 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 (error) {
console.log(error);
}); // Optionally the request above could also be done as
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) {
// Both requests are now complete
}));

当然,axios 的功能还包括 axios API、interceptor 等等,这里想要详细了解的可以查看官方文档:axios,后面陆续会介绍下 interceptor 的使用和各类参数的配置。

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 3.0 未本地化版本许可协议进行许可。 https://blog.csdn.net/xjlinme/article/details/77650059

最新文章

  1. MongoDB 分页查询的方法及性能
  2. 扩展当easyui datagrid无数据时,显示特定值。如:没有数据
  3. Git基本命令行操作 (转)
  4. memcache与memcached扩展的区别
  5. lazy instructor
  6. Service Reference
  7. vs2013 创建网站
  8. sort vector - leetcode 新用法
  9. meta标签使360浏览器默认极速模式
  10. BeginInvoke()使用
  11. shell 简单脚本编程
  12. python的学习笔记01_5文件操作
  13. Liunx服务管理(Centos)
  14. HTTP 错误 500.21 - Internal Server Error 处理程序“BlockViewHandler”在其模块列表中有一个错误模块“ManagedPipelineHandler
  15. python3 TypeError: a bytes-like object is required, not 'str'
  16. tchart example
  17. mysql数据库中如何查询日期在两个时间之间的关系
  18. ARM 常用汇编指令
  19. euclidea 3.0 全三星 攻略
  20. hadoop学习笔记(二):简单启动

热门文章

  1. [NOIP 2014] 生活大爆炸版石头剪刀布
  2. awk查找特定字段
  3. compare正序与逆序
  4. Chrome 最小化恢复之后部分黑屏
  5. POJ 1010 题目翻译+题解
  6. Discuze修改用户名长度限制
  7. nodejs __dirname 与 process.cwd()的区别
  8. Foeach 时修改集合的值报错
  9. Java 开源博客 Solo 1.2.0 发布 - 一键启动
  10. 【技术累积】【点】【Java】【12】几种常见编码(持续更新)