axios工具的使用

        axios 是一个基于 Promise 的 HTTP 客户端,广泛用于浏览器和 Node.js 环境中进行 HTTP 请求。它提供了简洁的 API,支持拦截请求和响应、取消请求、自动转换 JSON 数据等功能。

1. 安装 axios

        在使用 axios 之前,需要先安装它。可以通过 npm  进行安装:
npm install axios

2. 基本使用

(1)发送 GET 请求
 import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
(2)发送 POST 请求
import axios from 'axios';

axios.post('https://api.example.com/data', {
    key1: 'value1',
    key2: 'value2'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
(3)发送 PUT 请求
import axios from 'axios';

axios.put('https://api.example.com/data/1', {
    key1: 'new value1',
    key2: 'new value2'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });
(4)发送 DELETE 请求
import axios from 'axios';

axios.delete('https://api.example.com/data/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

3. 配置请求

        可以通过 axios.create()`创建一个自定义的 axios`实例,并在其中配置默认参数,如基础 URL、请求头等。

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

instance.get('/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

4. 拦截请求和响应

        axios 允许在请求或响应被处理之前拦截它们,进行一些自定义操作,如添加认证信息、处理错误等。

import axios from 'axios';

// 添加请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  config.headers.Authorization = 'Bearer your_token';
  return config;
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {
  // 对响应数据做些什么
  return response;
}, error => {
  // 对响应错误做些什么
  return Promise.reject(error);
});

5.总结

        axios`是一个功能强大且易于使用的 HTTP 客户端,适用于各种前端和后端项目。支持拦截请求和响应、取消请求、自动转换 JSON 数据等功能。

          因作者技术有限,有误之处欢迎大家评论区指出,如遇相关的其他问题,请在下面回复或者直接私信作者!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

l_lfei

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值