当前位置:首页 > 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);
  }
}

拦截器

添加请求或响应拦截器:

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

react如何引用axios

标签: reactaxios
分享给朋友:

相关文章

如何评价react native

如何评价react native

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

如何生成react代码

如何生成react代码

使用 Create React App 生成项目 安装 Node.js 后,通过命令行工具运行以下命令创建新项目: npx create-react-app my-app cd my-app npm…

如何优化react

如何优化react

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

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官方…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react如何读

react如何读

React 的发音 React 的发音为 /riˈækt/(音标),读作“瑞-艾克特”。其中: “Re” 发音类似英文单词 “read” 的开头部分。 “act” 发音与英文单词 “act” 一致。…