axios入门教程

axios入门教程

1、axios是什么

Axios 是一个基于  promise的 HTTP 库,可以用在浏览器和 node.js 中。

2、axios如何安装

(1)使用npm方式进行安装

npm install axios

(2)使用bower方式进行安装

bower install axios

(3)使用cdn方式进行安装

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

3、axios使用案例

(1)get请求方式

将请求参数拼接到url中

const axios = require('axios');
 
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });
 
 

将请求参数放到params

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

 想要使用异步/等待?在外部函数/方法中添加'async关键字。 

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

(2)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) {
    //2个post请求现已完成
  }));

4、整合vue-axios

(1)安装vue-axios

npm install --save axios vue-axios

(2)在main.js中加入

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)

(3)vue-axios使用方法

这里以get请求方式举例说明,其它请求方式类似。

Vue.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.axios.get(api).then((response) => {
  console.log(response.data)
})
 
this.$http.get(api).then((response) => {
  console.log(response.data)
})

 

文章链接: https://www.mfisp.com/12477.html

文章标题:axios入门教程

文章版权:梦飞科技所发布的内容,部分为原创文章,转载请注明来源,网络转载文章如有侵权请联系我们!

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

给TA打赏
共{{data.count}}人
人已打赏
建站教程投稿分享

宝塔的安装方法

2022-11-10 20:40:04

建站教程投稿分享

错误: 找不到或无法加载主类 xxxx

2022-11-17 23:40:30

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
客户经理
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索

梦飞科技 - 最新云主机促销服务器租用优惠