我连接到 server.js 文件中的数据库,并通过调用 API '/api/getAll' 获取 DataSensor.jsx 中的数据。但我的 UI 没有呈现任何内容,我打开控制台日志,它显示“获取传感器数据时出错:AxiosError”。请帮助我,我是新手。
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 连接到 mysql 数据库
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}`);
});
你的代码有点问题 您没有调用该函数,并且问题正在使用中,这里是更新的代码希望它会对您有所帮助
`import { useState, useEffect } from "react";
从 'axios' 导入 axios; 常量数据传感器 = () => {
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);
} catch (error) {
console.log('Error', error)
}
}
fetchData();
}
, []); // Empty dependency array means this effect will only run once (like component
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>
)
}
导出默认数据传感器;`