当前位置:首页 > React

react如何引用axios

2026-01-24 02:45:44React

安装 axios

在 React 项目中安装 axios 依赖:

npm install axios

或使用 yarn:

yarn add axios

导入 axios

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

import axios from 'axios';

发起 HTTP 请求

使用 axios 发起 GET 请求:

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

使用 axios 发起 POST 请求:

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 或 headers:

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

创建 axios 实例

如果需要多个不同配置的实例:

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

使用 async/await

结合 async/await 处理异步请求:

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    console.log(response.data);
  } catch (error) {
    console.error('Error:', error);
  }
}

拦截器

添加请求或响应拦截器:

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

标签: reactaxios
分享给朋友:

相关文章

如何学习react

如何学习react

学习 React 的步骤 理解基础概念 React 是一个用于构建用户界面的 JavaScript 库。学习 React 之前,建议掌握 JavaScript 的基础知识,包括 ES6+ 语法(如箭头…

如何手写一个react

如何手写一个react

手写一个简单的 React 创建一个基础的 React 实现需要理解其核心概念:虚拟 DOM、组件、状态管理和渲染。以下是一个简化版的 React 实现。 创建虚拟 DOM 虚拟 DOM 是真实 D…

如何优化react

如何优化react

优化 React 性能的方法 使用 React.memo 或 PureComponent 对于函数组件,使用 React.memo 进行记忆化,避免不必要的重新渲染。类组件可以使用 PureCompo…

react如何遍历

react如何遍历

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

react如何验证

react如何验证

表单验证方法 在React中验证表单数据通常使用以下几种方式: 内置HTML5验证 利用HTML5原生表单验证属性如required、pattern等,结合form.noValidate属性禁用浏览…

理解如何react

理解如何react

理解React的核心概念 React是一个用于构建用户界面的JavaScript库,专注于通过组件化开发提高代码的可维护性和复用性。其核心思想包括虚拟DOM(Virtual DOM)和单向数据流,能够…