Axios请求库

一、什么是Axios

Axios是一个常用的 JavaScript HTTP 请求库,因其易用性和强大的功能,在前端开发中得到了广泛应用,特别是在与 RESTful API 交互的单页面应用(SPA)中。使用 Axios 可以简化 HTTP 请求的发送和处理,使得与后端服务的交互更加直接和高效。

二、Axios如何发请求

2.1 使用npm或者yarn包管理工具安装axios

npm install axios
// 或
yarn add axios

2.2 基本的四大请求 

基于链式编写的方式,基本的写法都是按照axios.get/post/delete/put.then().catch()这样的写法去写的,在对应的回调函数中我们可以去处理接收的响应对象。then()为成功响应并接收到服务端传递过来的json对象,catch()为我们捕捉到的错误信息。

1:发送GET请求

axios.get('https://example.com/api/data')
 .then(response => {
    // 成功时的处理逻辑
    console.log(response.data); // 响应的数据
    console.log(response.status); // 响应的状态码
    console.log(response.statusText); // 状态码的文本描述
    console.log(response.headers); // 响应的头信息
  })
 .catch(error => {
    // 错误处理逻辑
    if (error.response) {
      // 请求已发出,但服务器响应的状态码不在 2xx 范围内
      console.error(error.response.data);
      console.error(error.response.status);
      console.error(error.response.headers);
    } else if (error.request) {
      // 请求已发出,但没有收到响应
      console.error(error.request);
    } else {
      // 发生了其他错误,设置请求时出错
      console.error('Error', error.message);
    }
  });

2: 发送POST请求

axios.post('https://example.com/api/submit', {
  key1: 'value1',
  key2: 'value2'
})
 .then(response => {
    // 处理成功响应
  })
 .catch(error => {
    // 处理错误
  });

其中,key1,key2的键值对,代表我们所提交的数据对象。

3:发送DELETE请求 

axios.delete('https://example.com/api/delete-item?id=1')
 .then(response => {
    // 处理成功响应
  })
 .catch(error => {
    // 处理错误
  });

4:发送PUT请求 

axios.put('https://example.com/api/update', {
  // 要更新的数据
})
 .then(response => {
    // 处理成功响应
  })
 .catch(error => {
    // 处理错误
  });

2.3  以对象形式发送请求

axios还提供了另外一种发送请求的方式,区别于上面以.get/.post/.delete/.put等方式,axios还能以对象配置的方式发请求。

区别主要在于,我们可以直接写一个对象,指定method(请求方式),url(请求路径),data(数据对象,通常是post/put所提交的对象),headers(请求头),timeout(请求超时时间),

随后,跟上述方式一样,在then里面处理接收到的对象,catch捕捉错误处理。

axios({
  method: 'POST', // 请求方法,如 'GET', 'POST', 'PUT', 'DELETE' 等
  url: 'https://example.com/api/submit', // 请求的 URL
  data: { // 要发送的数据,如果是 POST、PUT 等请求通常放在这里
    key1: 'value1',
    key2: 'value2'
  },
  headers: { // 自定义请求头
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your_token'
  },
  timeout: 5000 // 设置超时时间(毫秒)
})
.then(response => {
  // 成功时的处理逻辑
  console.log(response.data);
})
.catch(error => {
  // 错误处理逻辑
  if (error.response) {
    // 服务器有响应,但状态码不在 2xx 范围内
    console.error(error.response.data);
    console.error(error.response.status);
    console.error(error.response.headers);
  } else if (error.request) {
    // 发送请求但未收到响应
    console.error(error.request);
  } else {
    // 其他错误
    console.error('Error', error.message);
  }
});
  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值