当前位置:首页 > React

react如何引用axios

2026-02-26 16:41:15React

安装 Axios

在 React 项目中安装 Axios,可以通过 npm 或 yarn 完成。打开终端并运行以下命令之一:

npm install axios
yarn add axios

导入 Axios

在需要使用 Axios 的组件或文件中,通过 import 语句引入 Axios:

import axios from 'axios';

发起 HTTP 请求

使用 Axios 发起 GET、POST、PUT、DELETE 等请求。以下是一些常见请求的示例:

GET 请求示例:

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

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);
  });

全局配置

可以设置 Axios 的全局配置,例如默认的 baseURL 或请求头:

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

创建 Axios 实例

如果需要为不同 API 设置不同的配置,可以创建独立的 Axios 实例:

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

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

拦截器

Axios 支持请求和响应拦截器,可以在请求发送前或响应返回后添加逻辑:

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 的 CancelToken 可以取消未完成的请求:

const source = axios.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.');

标签: reactaxios
分享给朋友:

相关文章

react如何测试

react如何测试

React 测试方法 React 应用的测试通常涉及组件测试、集成测试和端到端测试。以下是常用的测试工具和方法: Jest Jest 是 Facebook 开发的 JavaScript 测试框架,适…

如何改造react

如何改造react

改造 React 项目的关键方法 分析当前项目结构 通过评估现有组件、状态管理和依赖项,明确需要改进的部分。使用工具如 webpack-bundle-analyzer 识别性能瓶颈。 升级 Reac…

react如何遍历

react如何遍历

遍历数组或对象的方法 在React中,遍历数组或对象通常用于渲染列表或动态生成内容。以下是几种常见的遍历方法: 使用map遍历数组map是遍历数组并返回新数组的高阶函数,适合渲染列表。 con…

react项目如何启动

react项目如何启动

启动React项目的步骤 确保已安装Node.js(建议版本12以上)和npm/yarn。可通过以下命令检查版本: node -v npm -v 全局安装create-react-app脚手架工具(…

react参数如何传递

react参数如何传递

参数传递方式 React 中参数传递主要有以下几种方式: Props 传递 父组件通过属性(props)向子组件传递数据。子组件通过 props 对象接收参数。 // 父组件 <Chil…

如何学react native

如何学react native

学习React Native的路径 掌握JavaScript和React基础知识是学习React Native的前提。熟悉ES6+语法、组件生命周期、状态管理和Hooks等概念能够帮助更快上手Reac…