无法从数据库取数并渲染到UI表格,请求技术协助
问题:React组件调用接口获取数据失败,UI无渲染,控制台报AxiosError
我已经在server.js中完成MySQL数据库连接,在DataSensor.jsx组件内调用/api/getAll接口获取数据,但UI未渲染任何内容,控制台提示“Error fetching sensor data: AxiosError”。我是新手,恳请帮助解决该问题。
前端DataSensors.jsx代码
import React, { useEffect, useState } from 'react' import axios from 'axios'; import '../styles/datasensors.css' const DataSensors = () => { const [sensorData, setSensorData] = useState([]); useEffect(() => { const fetchData = async () => { try { const response = await axios.get('/api/getAll'); console.log('Data received:', response.data); setSensorData(response.data); return ( <div className='container__data'> <table className='data-table'> <thead> <tr> <th>ID</th> <th>Temperature</th> <th>Humidity</th> <th>Brightness</th> <th>Created At</th> </tr> </thead> <tbody> {sensorData.map((data) => ( <tr key={data.id}> <td>{data.id}</td> <td>{data.temperature}</td> <td>{data.humidity}</td> <td>{data.brightness}</td> <td>{data.createdAt}</td> </tr> ))} </tbody> </table> </div> ) } export default DataSensors;
后端server.js代码
const express = require('express'); const bodyParser = require('body-parser'); const mysql = require('mysql2'); const cors = require('cors'); const app = express(); const port = 3002; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true})); app.use(cors()); const db = mysql.createConnection({ host: 'localhost', user: 'root', password: '123456', database: 'iot' }); app.get('/api/getAll', (req, res) => { const sql = 'SELECT * FROM datasensors'; db.query(sql, (err, result) => { if( err ) { console.error('Error executing query:', err); res.status(500).json({err: 'Internal Server Error'}); } else { console.log('Data from database:', result); res.status(200).json(result); } }); }); db.connect(err => { if( err ) { console.error("Lỗi kết nối tới cơ sở dữ liệu MySQL: " + err.stack); return; } console.log("Kết nối thành công đến cơ sở dữ liệu MySQL"); }) app.listen(port, () => { console.log(`Server đang lắng nghe tại http://localhost:${port}`); });
排查与解决步骤
1. 修复React组件语法错误
你的前端代码存在未闭合的代码块:useEffect内部的fetchData函数、try代码块都没有闭合,直接导致组件无法正常编译运行。修复后的完整代码:
import React, { useEffect, useState } from 'react' import axios from 'axios'; import '../styles/datasensors.css' const DataSensors = () => { const [sensorData, setSensorData] = useState([]); useEffect(() => { const fetchData = async () => { try { // 注意:如果前后端端口不同,必须写完整后端地址 const response = await axios.get('http://localhost:3002/api/getAll'); console.log('Data received:', response.data); setSensorData(response.data); } catch (error) { console.error('Error fetching sensor data:', error); } }; fetchData(); }, []); // 空依赖数组确保组件挂载时仅执行一次 return ( <div className='container__data'> <table className='data-table'> <thead> <tr> <th>ID</th> <th>Temperature</th> <th>Humidity</th> <th>Brightness</th> <th>Created At</th> </tr> </thead> <tbody> {sensorData.map((data) => ( <tr key={data.id}> <td>{data.id}</td> <td>{data.temperature}</td> <td>{data.humidity}</td> <td>{data.brightness}</td> <td>{data.createdAt}</td> </tr> ))} </tbody> </table> </div> ) } export default DataSensors;
2. 修正接口调用地址
后端服务运行在3002端口,如果前端项目运行在其他端口(比如默认的3000),直接用/api/getAll会请求前端服务地址,导致404或跨域错误。解决方式二选一:
- 直接在请求中写完整后端地址:
http://localhost:3002/api/getAll - 在前端项目的
package.json中添加代理配置,这样可以继续用相对路径:"proxy": "http://localhost:3002"
3. 验证后端接口可用性
打开浏览器直接访问http://localhost:3002/api/getAll:
- 如果返回500错误:检查后端控制台的数据库连接、SQL查询日志,确认数据库
iot存在,表datasensors的字段名(比如createdAt)和前端使用的一致 - 如果返回404:确认后端服务正常运行在
3002端口,路由/api/getAll正确注册 - 如果返回正常数据:说明后端没问题,重点检查前端代码的语法和请求地址
4. 确认跨域配置
后端已经添加cors中间件,这部分无需调整,但要确保前后端端口不同时,请求地址或代理配置正确。
内容的提问来源于stack exchange,提问作者TunazZz
相关产品推荐
相关产品推荐

