当前位置:首页 > React

react中如何使用axios

2026-01-24 22:42:27React

安装 axios

在项目中安装 axios 依赖:

npm install axios
# 或使用 yarn
yarn add axios

引入 axios

在需要使用 axios 的组件或文件中引入:

import axios from 'axios';

发起 GET 请求

使用 axios.get 发起 GET 请求:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

发起 POST 请求

使用 axios.post 发起 POST 请求:

react中如何使用axios

axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });

配置全局默认值

可以设置全局默认配置,如 baseURL 或 headers:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';

创建实例

通过 axios.create 创建自定义实例:

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 5000,
});

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

拦截请求和响应

添加请求和响应拦截器:

react中如何使用axios

// 请求拦截器
axios.interceptors.request.use(config => {
  console.log('Request sent:', config);
  return config;
}, error => {
  return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(response => {
  console.log('Response received:', response);
  return response;
}, error => {
  return Promise.reject(error);
});

处理并发请求

使用 axios.allaxios.spread 处理并发请求:

axios.all([
  axios.get('https://api.example.com/data1'),
  axios.get('https://api.example.com/data2')
])
.then(axios.spread((response1, response2) => {
  console.log(response1.data, response2.data);
}));

取消请求

使用 CancelToken 取消请求:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('https://api.example.com/data', {
  cancelToken: source.token
})
.catch(error => {
  if (axios.isCancel(error)) {
    console.log('Request canceled:', error.message);
  }
});

// 取消请求
source.cancel('Operation canceled by the user.');

错误处理

统一处理错误:

axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      console.error('Server responded with error status:', error.response.status);
    } else if (error.request) {
      console.error('No response received:', error.request);
    } else {
      console.error('Error setting up request:', error.message);
    }
  });

分享给朋友:

相关文章

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取日期 在 React 项目中,可以通过 Moment.js 库轻松处理日期和时间。以下是几种常见的日期获取方法。 安装 Moment.js 确保项目中已安装 Momen…

react 如何执行

react 如何执行

安装 React 确保 Node.js 安装在本地环境中。通过以下命令创建新的 React 项目: npx create-react-app my-app 进入项目目录并启动开发服务器:…

react如何保养

react如何保养

保持组件简洁 将大型组件拆分为更小、更专注的组件,每个组件只负责单一功能。避免在单个组件中处理过多逻辑或状态,这有助于提高可维护性和可测试性。 合理使用状态管理 根据应用复杂度选择状态管理方案。简单…

如何react页面

如何react页面

创建 React 页面 使用 create-react-app 快速初始化项目: npx create-react-app my-app cd my-app npm start 编写组件代码 在 s…

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

如何评价react native

如何评价react native

React Native 的优势 跨平台开发效率高:基于 JavaScript 和 React 语法,可同时开发 iOS 和 Android 应用,减少重复代码量。性能接近原生:通过原生组件渲染,性能…