Код: Выделить всё
// server.js
import express from "express";
import mysql from "mysql2";
const app = express();
const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "testdb"
});
app.get("/api/users", (req, res) => {
db.query("SELECT * FROM users", (err, results) => {
if (err) return res.status(500).json({ error: err.message });
res.json(results);
});
});
app.listen(5000, () => console.log("Server running on port 5000"));
Код: Выделить всё
// pages/index.js
import { useEffect, useState } from "react";
export default function Home() {
const [users, setUsers] = useState([]);
useEffect(() => {
fetch("http://localhost:5000/api/users")
.then((res) => res.json())
.then((data) => setUsers(data))
.catch((err) => console.error(err));
}, []);
return (
User List
[list]
{users.map((u) => (
[*]{u.name}
))}
[/list]
);
}
Я уже проверял:
Express API работает нормально, когда вызывает непосредственно.
функциональ. />
Код: Выделить всё
TypeError: Cannot read properties of undefined (reading 'map')Подробнее здесь: https://stackoverflow.com/questions/797 ... ss-backend
Мобильная версия