axios 全攻略之基本介绍与使用(GET 与 POST)

古城微笑少年丶 2022-06-09 05:11 262阅读 0赞

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

  1. // Make a request for a user with a given ID
  2. axios.get('/user?ID=12345')
  3. .then(function (response) {
  4. console.log(response);
  5. })
  6. .catch(function (error) {
  7. console.log(error);
  8. });
  9. // Optionally the request above could also be done as
  10. axios.get('/user', {
  11. params: {
  12. ID: 12345
  13. }
  14. })
  15. .then(function (response) {
  16. console.log(response);
  17. })
  18. .catch(function (error) {
  19. console.log(error);
  20. });

POST

  1. axios.post('/user', {
  2. firstName: 'Fred',
  3. lastName: 'Flintstone'
  4. })
  5. .then(function (response) {
  6. console.log(response);
  7. })
  8. .catch(function (error) {
  9. console.log(error);
  10. });

同时发送多个请求

  1. function getUserAccount() {
  2. return axios.get('/user/12345');
  3. }
  4. function getUserPermissions() {
  5. return axios.get('/user/12345/permissions');
  6. }
  7. axios.all([getUserAccount(), getUserPermissions()])
  8. .then(axios.spread(function (acct, perms) {
  9. // Both requests are now complete
  10. }));

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

发表评论

表情:
评论列表 (有 0 条评论,262人围观)

还没有评论,来说两句吧...

相关阅读

    相关 axios get / post request

    五:axios:         axios并不是vue插件,所以不能使用Vue.use(),所以只能在每个需要发送请求的组件中即时引入。为了解决这个问题,可以在引入 axi

    相关 vue axios

    随着 vuejs 作者尤雨溪发布消息,不再继续维护`vue-resource`,并推荐大家使用 `axios` 开始,`axios` 被越来越多的人所了解。本来想在网上找找详细