Vue.js 学习笔记十六:Axios 之基本使用

目录

基本使用

发起一个 GET 请求

发起一个 POST 请求

发送并发请求


基本使用

先说一下怎么安装和引入:

npm install axios --save
import axios from 'axios'    //使用前引入

axios 有很多请求方式,具体可以看一下官网的 API,下面先学习最基本的使用方式。

发起一个 GET 请求

axios.get(url[, config])

import axios from 'axios'

// 向给定id的用户发起请求
axios.get('http://127.0.0.1:8000/user?id=1')
  .then(function (res) {
    // 处理成功情况
    console.log(res);
  })
  .catch(function (error) {
    // 处理错误情况
    console.log(error);
  })
  .then(function () {
    // 总是会执行
  });

// 上述请求也可以按以下方式完成(可选)
axios.get('http://127.0.0.1:8000/user', {
    params: {
      id: 1
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // 总是会执行
  });  

// 支持async/await用法
async function getUser() {
  try {
    const res = await axios.get('http://127.0.0.1:8000/user?id=1');
    console.log(res);
  } catch (error) {
    console.error(error);
  }
}

发起一个 POST 请求

axios.post(url[, data[, config]])

axios.post('http://127.0.0.1:8000/user/add', {
    name: 'stary',
    age: 18
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (error) {
    console.log(error);
  });

发送并发请求

axios.all([]) 返回的结果是一个数组,使用 axios.spread 可将数组 [res1,res2] 展开为 res1, res2

function getUserInfo() {
  return axios.get('http://127.0.0.1:8000/user/1');
}

function getUserRole() {
  return axios.get('http://127.0.0.1:8000/user/role?userId=1');
}

axios.all([getUserInfo(), getUserRole()])
  .then(function (res) {
    console.log(res[0])
    console.log(res[1])
})

// 使用 `axios.spread`
axios.all([getUserInfo(), getUserRole()])
  .then(
    axios.spread((res1, res2) => {
		console.log(res1)
		console.log(res2)
	})
);

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stary1993

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值