求React教程:通过按钮调用Spring Boot接口并展示JSON响应
从零实现React调用Spring Boot接口并展示数据的简单教程
1. 准备React基础项目(如果还没有)
如果还没创建React项目,用官方脚手架快速生成:
npx create-react-app spring-boot-react-demo cd spring-boot-react-demo
2. 编写核心组件(ApiCaller.js)
在src目录下新建ApiCaller.js和ApiCaller.css,下面是包含GET/POST请求实现的完整组件代码:
import { useState } from 'react'; import './ApiCaller.css'; function ApiCaller() { // 存储接口返回的数据 const [apiData, setApiData] = useState(null); // 存储加载状态 const [isLoading, setIsLoading] = useState(false); // 存储错误信息 const [error, setError] = useState(null); // 处理GET请求 const handleGetRequest = async () => { setIsLoading(true); setError(null); try { // 替换成你的Spring Boot GET接口地址,比如http://localhost:8080/api/data const response = await fetch('http://localhost:8080/api/get-data'); if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); // 自动解析JSON响应 setApiData(data); } catch (err) { setError(err.message); } finally { setIsLoading(false); } }; // 处理POST请求(带JSON参数) const handlePostRequest = async () => { setIsLoading(true); setError(null); try { // 替换成你的Spring Boot POST接口地址 const response = await fetch('http://localhost:8080/api/post-data', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: 'test', age: 25 }), // 要发送的JSON参数 }); if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); setApiData(data); } catch (err) { setError(err.message); } finally { setIsLoading(false); } }; return ( <div className="api-caller-container"> <div className="button-group"> <button onClick={handleGetRequest} disabled={isLoading}> {isLoading ? '加载中...' : '发起GET请求'} </button> <button onClick={handlePostRequest} disabled={isLoading}> {isLoading ? '加载中...' : '发起POST请求'} </button> </div> {/* 错误信息展示 */} {error && <div className="error-message">❌ {error}</div>} {/* 数据展示区域 */} <div className="data-display"> {isLoading ? ( <p>正在加载数据...</p> ) : apiData ? ( <pre>{JSON.stringify(apiData, null, 2)}</pre> // 格式化展示JSON ) : ( <p>点击按钮发起请求获取数据</p> )} </div> </div> ); } export default ApiCaller;
3. 添加简单样式(ApiCaller.css)
在ApiCaller.css里添加基础样式,让界面更清晰:
.api-caller-container { max-width: 800px; margin: 50px auto; padding: 20px; font-family: Arial, sans-serif; } .button-group { margin-bottom: 20px; } button { padding: 10px 20px; margin-right: 10px; border: none; border-radius: 4px; background-color: #007bff; color: white; cursor: pointer; font-size: 16px; } button:disabled { background-color: #6c757d; cursor: not-allowed; } .error-message { color: #dc3545; padding: 10px; border: 1px solid #dc3545; border-radius: 4px; margin-bottom: 20px; } .data-display { padding: 20px; border: 1px solid #dee2e6; border-radius: 4px; background-color: #f8f9fa; } pre { white-space: pre-wrap; word-wrap: break-word; margin: 0; }
4. 在App.js中引入组件
修改src/App.js,把我们的组件加入到页面中:
import ApiCaller from './ApiCaller'; function App() { return ( <div className="App"> <ApiCaller /> </div> ); } export default App;
5. 解决跨域问题(关键!)
React默认运行在http://localhost:3000,Spring Boot通常在http://localhost:8080,浏览器会拦截跨域请求,需要在Spring Boot后端配置跨域:
- 方式1:在接口控制器上添加
@CrossOrigin注解:
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = "http://localhost:3000") // 允许React域名访问 public class DataController { @GetMapping("/api/get-data") public Object getData() { // 返回你的JSON数据 return "{\"id\":1,\"name\":\"测试数据\",\"status\":\"success\"}"; } }
- 方式2:全局跨域配置(适合多个接口),新建配置类:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class CorsConfig { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**") // 匹配所有/api开头的接口 .allowedOrigins("http://localhost:3000") // 允许React域名 .allowedMethods("GET", "POST") // 允许的请求方法 .allowedHeaders("*"); } }; } }
6. 运行测试
- 启动Spring Boot后端,确保接口可正常访问
- 启动React项目:
npm start,打开http://localhost:3000 - 点击按钮,即可看到接口返回的JSON数据被格式化展示
内容的提问来源于stack exchange,提问作者Curnell
相关产品推荐
相关产品推荐

