如何通过Node/Express获取RapidAPI数据并在React前端渲染
解决方案
一、确认后端服务正常运行
你的server.js已经完成了基础配置,先确保以下步骤执行到位:
- 安装所有依赖:
npm install express cors dotenv axios - 根目录创建
.env文件,填入你的RapidAPI密钥:RAPID_API_KEY=你的密钥内容 - 启动后端服务:
node server.js,控制台输出Server started on port8000后,访问http://localhost:8000/team,确认能返回正常的JSON数据。
二、React前端获取数据并渲染HTML
修改App.js,借助React的状态管理和生命周期钩子实现数据请求与渲染:
import React, { useState, useEffect } from 'react' function App() { // 定义状态存储数据、加载状态和错误信息 const [teamData, setTeamData] = useState(null) const [isLoading, setIsLoading] = useState(true) const [fetchError, setFetchError] = useState(null) // 组件挂载时发起请求 useEffect(() => { const getTeamStats = async () => { try { const res = await fetch('http://localhost:8000/team') if (!res.ok) throw new Error('数据请求失败') const data = await res.json() setTeamData(data) } catch (err) { setFetchError(err.message) } finally { setIsLoading(false) } } getTeamStats() }, []) // 根据状态渲染对应内容 if (isLoading) return <div>加载中...</div> if (fetchError) return <div>出错了:{fetchError}</div> if (!teamData) return <div>暂无数据</div> // 从返回的JSON中提取需要展示的字段(适配RapidAPI的teams/statistics接口结构) const stats = teamData.response[0] return ( <div style={{ padding: '2rem', maxWidth: '800px', margin: '0 auto' }}> <h1>{stats.team.name} 2020赛季统计</h1> <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '1rem', margin: '2rem 0' }}> <div style={{ padding: '1rem', border: '1px solid #eee', borderRadius: '8px' }}> <h3>联赛排名</h3> <p style={{ fontSize: '1.5rem', fontWeight: 'bold' }}>{stats.league.rank}</p> </div> <div style={{ padding: '1rem', border: '1px solid #eee', borderRadius: '8px' }}> <h3>总场次</h3> <p style={{ fontSize: '1.5rem', fontWeight: 'bold' }}>{stats.fixtures.played.total}</p> </div> <div style={{ padding: '1rem', border: '1px solid #eee', borderRadius: '8px' }}> <h3>胜场数</h3> <p style={{ fontSize: '1.5rem', fontWeight: 'bold' }}>{stats.fixtures.wins.total}</p> </div> <div style={{ padding: '1rem', border: '1px solid #eee', borderRadius: '8px' }}> <h3>总进球</h3> <p style={{ fontSize: '1.5rem', fontWeight: 'bold' }}>{stats.goals.for.total.total}</p> </div> </div> <h2>近期赛事</h2> <ul style={{ listStyle: 'none', padding: 0 }}> {stats.fixtures.recent.map((match, idx) => ( <li key={idx} style={{ padding: '1rem', borderBottom: '1px solid #eee' }}> <p>{match.date.split('T')[0]} | {match.homeTeam.name} vs {match.awayTeam.name}</p> <p>比分:{match.goals.home} - {match.goals.away}</p> </li> ))} </ul> </div> ) } export default App
三、补充说明
- 字段适配:如果RapidAPI返回的JSON结构有变动,需要对应调整
stats下的取值路径。 - 请求工具替代:也可以用
axios代替原生fetch,先执行npm install axios,再将请求部分替换为:const res = await axios.get('http://localhost:8000/team') const data = res.data - 样式优化:示例用内联样式做基础展示,实际开发中可以提取CSS类或者使用CSS框架美化。
内容的提问来源于stack exchange,提问作者Jaiylon
相关产品推荐
相关产品推荐

