React 中使用 Axios 进行 HTTP 请求

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

1. 安装 Axios

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

bash 复制代码
npm install axios

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

项目结构:

css 复制代码
src/
├── App.js
├── services/
│   └── api.js

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

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

javascript 复制代码
// 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 发起请求:

javascript 复制代码
// 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. 效果截图

初始状态:显示已有帖子。如图:

提交后:新帖子会添加到列表顶部。如图:

相关推荐
Miketutu1 天前
Flutter学习 - 组件通信与网络请求Dio
开发语言·前端·javascript
摘星编程1 天前
React Native for OpenHarmony 实战:Swiper 滑动组件详解
javascript·react native·react.js
鸣弦artha1 天前
Flutter框架跨平台鸿蒙开发——Build流程深度解析
开发语言·javascript·flutter
掘根1 天前
【jsonRpc项目】常用的零碎功能接口实现
网络协议·http
摘星编程1 天前
React Native for OpenHarmony 实战:DisplayInfo 显示信息详解
android·react native·react.js
LongJ_Sir1 天前
Cesium--可拖拽气泡弹窗(Vue3版)
javascript
跟着珅聪学java1 天前
JavaScript 中定义全局变量的教程
javascript
哈哈你是真的厉害1 天前
React Native 鸿蒙跨平台开发:FlatList 基础列表代码指南
react native·react.js·harmonyos
午安~婉1 天前
整理知识点
前端·javascript·vue
向前V1 天前
Flutter for OpenHarmony数独游戏App实战:底部导航栏
javascript·flutter·游戏