Vue3实战笔记(06)--- Axios 基本用法


前言

今天学习Vue官方推荐的请求工具Axios ,Axios 是一个基于 promise 的 HTTP 库,可用于浏览器和 node.js 中。它简洁、易用且功能强大,支持多种请求类型(GET、POST、PUT、DELETE 等),能够自动转换请求和响应数据(如JSON数据),并且提供了拦截请求和响应、取消请求、配置默认参数等多种功能,使得在进行 AJAX 请求时更加便捷和高效。


一、发送get请求

不多说了,直接实战示例,多看注释:


const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

// 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);
  })
  .finally(function () {
    // always executed
  });  

// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

二、发送post请求

示例:

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  
  //表单作为参数:
  const {data} = await axios.post('/user', document.querySelector('#my-form'), {
  headers: {
    'Content-Type': 'application/json'
  }
  })
  
  //执行混合的请求:
  function getUserAccount() {
  return axios.get('/user/12345');
  }

  function getUserPermissions() {
    return axios.get('/user/12345/permissions');
  }
  
  const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);
  
  // OR
  
  Promise.all([getUserAccount(), getUserPermissions()])
    .then(function ([acct, perm]) {
      // ...
   });
   
   
// 表单文件相关:Multipart (multipart/form-data)  
 const {data} = await axios.post('https://httpbin.org/post', {
    firstName: 'Fred',
    lastName: 'Flintstone',
    orders: [1, 2, 3],
    photo: document.querySelector('#fileInput').files
    }, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
  )
  URL encoded form (application/x-www-form-urlencoded)
   const {data} = await axios.post('https://httpbin.org/post', {
    firstName: 'Fred',
    lastName: 'Flintstone',
    orders: [1, 2, 3]
  }, {
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
   

三、另一种写法

代码如下(示例):

axios(config)
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// GET request for remote image in node.js
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });
axios(url[, config])
// Send a GET request (default method)这是最简单的默认方式,get请求
axios('/user/12345');
//Request method aliases
//For convenience aliases have been provided for all supported request methods. --别名

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
axios.postForm(url[, data[, config]])
axios.putForm(url[, data[, config]])
axios.patchForm(url[, data[, config]])

总结

Axios 因其灵活性和易用性,成为了现代前端开发中非常流行的HTTP库之一,广泛应用于各种Web项目中。今天内容比较多,需要大量时间实战测试和体会才能熟练应用。

相关推荐

  1. Vue3实战笔记06)--- Axios 基本

    2024-05-13 08:08:07       15 阅读
  2. Vue3实战笔记07)— Axios进阶与提高

    2024-05-13 08:08:07       11 阅读
  3. Vue基本

    2024-05-13 08:08:07       21 阅读
  4. vue开发,axios网络请求框架基本和封装

    2024-05-13 08:08:07       31 阅读
  5. vue3中ts的基本

    2024-05-13 08:08:07       32 阅读
  6. axios

    2024-05-13 08:08:07       8 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-05-13 08:08:07       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-05-13 08:08:07       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-05-13 08:08:07       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-05-13 08:08:07       18 阅读

热门阅读

  1. iOS ------ MRC

    2024-05-13 08:08:07       8 阅读
  2. axios的安装和引入

    2024-05-13 08:08:07       6 阅读
  3. AI学习指南概率论篇-期望和方差

    2024-05-13 08:08:07       13 阅读
  4. MPLS技术基础

    2024-05-13 08:08:07       10 阅读
  5. Gone框架介绍16 - 自动生成Priest

    2024-05-13 08:08:07       12 阅读
  6. 39-1 Web应用防火墙 - WAF应用程序层绕过

    2024-05-13 08:08:07       9 阅读
  7. PHP笔记

    PHP笔记

    2024-05-13 08:08:07      11 阅读
  8. 什么事防抖和节流,有什么区别,如何实现

    2024-05-13 08:08:07       7 阅读