当前位置: 首页 > article >正文

React 中使用 Axios 进行 HTTP 请求

下面是一个案例,展示如何在 React 中使用 Axios 进行 HTTP 请求,包括 GET 和 POST 请求的使用。

1. 安装 Axios

确保项目中已安装 Axios,可以通过以下命令安装:

npm install axios

2. 创建一个简单的 React 应用

项目结构:

src/
├── App.js
├── services/
│   └── api.js

在这里插入图片描述

(1) 在 services/api.js 中封装 Axios 实例:

封装 Axios 实例可以统一管理请求,比如添加 Base URL 和请求拦截器。

// src/services/api.js
import axios from 'axios';

// 创建 Axios 实例
const api = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com', // API 基础地址
  timeout: 10000, // 超时时间
});

// 添加请求拦截器
api.interceptors.request.use(
  (config) => {
    // 在请求发送之前做一些处理,比如添加 token
    console.log('请求拦截器:', config);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 添加响应拦截器
api.interceptors.response.use(
  (response) => {
    console.log('响应拦截器:', response);
    return response.data; // 直接返回数据
  },
  (error) => {
    console.error('响应错误:', error);
    return Promise.reject(error);
  }
);

export default api;

(2) 在 App.js 中使用 Axios 发起请求:

// src/App.js
import React, { useEffect, useState } from 'react';
import api from './services/api';

function App() {
  const [posts, setPosts] = useState([]);
  const [newPost, setNewPost] = useState({ title: '', body: '' });
  const [loading, setLoading] = useState(false);

  // GET 请求:获取数据
  useEffect(() => {
    const fetchPosts = async () => {
      setLoading(true);
      try {
        const data = await api.get('/posts');
        setPosts(data.slice(0, 5)); // 仅展示前 5 条
      } catch (error) {
        console.error('获取帖子失败:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchPosts();
  }, []);

  // POST 请求:提交数据
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const data = await api.post('/posts', newPost);
      setPosts([data, ...posts]); // 添加新帖子到列表
      setNewPost({ title: '', body: '' }); // 清空表单
    } catch (error) {
      console.error('提交帖子失败:', error);
    }
  };

  return (
    <div style={{ padding: '20px' }}>
      <h1>Axios 示例</h1>

      {/* 加载状态 */}
      {loading && <p>加载中...</p>}

      {/* 显示帖子列表 */}
      <ul>
        {posts.map((post) => (
          <li key={post.id}>
            <h3>{post.title}</h3>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>

      {/* 添加新帖子 */}
      <form onSubmit={handleSubmit} style={{ marginTop: '20px' }}>
        <input
          type="text"
          placeholder="标题"
          value={newPost.title}
          onChange={(e) => setNewPost({ ...newPost, title: e.target.value })}
          required
          style={{ marginRight: '10px' }}
        />
        <textarea
          placeholder="内容"
          value={newPost.body}
          onChange={(e) => setNewPost({ ...newPost, body: e.target.value })}
          required
          style={{ marginRight: '10px' }}
        />
        <button type="submit">提交</button>
      </form>
    </div>
  );
}

export default App;

3. 功能说明:

页面加载时,通过 useEffect 调用 api.get 获取帖子数据。
用户可以通过表单提交新的帖子,调用 api.post 将数据发送到服务器。
请求和响应都通过封装好的 Axios 实例处理,支持拦截器统一管理。

4. 效果截图

初始状态:显示已有帖子。如图:
在这里插入图片描述
提交后:新帖子会添加到列表顶部。如图:
在这里插入图片描述


http://www.kler.cn/a/402735.html

相关文章:

  • 国内docker pull拉取镜像的解决方法
  • SpringBoot+Vue 2 多方法实现(图片/视频/报表)文件上传下载,示例超详细 !
  • Vue 3 组件通信:深入理解 Props 和 Emits 的使用与最佳实践
  • 【Spring MVC】初步了解Spring MVC的基本概念与如何与浏览器建立连接
  • 库的操作(MySQL)
  • 【设计模式】【创建型模式(Creational Patterns)】之抽象工厂模式(Abstract Factory Pattern)
  • 探索C/C++的奥秘之list
  • 实验室资源调度系统:基于Spring Boot的创新
  • 技术总结(三十三)
  • Flink使用详解
  • 【5】GD32H7xx CAN发送及FIFO接收
  • React 远程仓库拉取项目部署,无法部署问题
  • 【VTK】MFC中使用VTK9.3
  • 1+X应急响应(网络)威胁情报分析:
  • 百度遭初创企业指控抄袭,维权还是碰瓷?
  • Github 2024-11-20C开源项目日报 Top9
  • 【Python项目】基于Python的医疗知识图谱问答系统
  • 低代码开发平台搭建思考与实战
  • ftdi_sio应用学习笔记 2 - 操作串口
  • Linux系统之lsblk命令的基本使用