当前位置:首页 > 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 native 如何

react native 如何

安装 React Native 开发环境 确保系统已安装 Node.js(建议版本 16 或更高)。通过以下命令安装 React Native CLI 工具: npm install -g reac…

react如何发音

react如何发音

React的发音 React的正确发音为 /riˈækt/,类似于“ree-akt”。以下是详细说明: 发音分解 第一个音节“Ree”发音类似英文单词“see”中的“ee”音。…

如何提高react

如何提高react

优化性能 使用React.memo对组件进行记忆化处理,避免不必要的重新渲染。对于类组件,可以使用PureComponent来达到类似效果。 利用useMemo缓存计算结果,避免重复计算。对于函数或…

如何调试react

如何调试react

调试 React 应用的方法 使用 React Developer Tools 安装浏览器扩展(Chrome/Firefox),通过组件树查看组件状态、props 和 hooks。支持实时编辑 pro…

小白如何搭建react

小白如何搭建react

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包(https://nodejs.org/),选择 LTS 版本。安装完成后,终端运行以下命令验证版…

react如何引入jq

react如何引入jq

在React中引入jQuery的方法 React和jQuery可以共存,但需要注意避免直接操作DOM,因为React有自己的虚拟DOM机制。以下是几种引入jQuery的方式: 通过npm安装jQue…