英文:
Couldn't fetch Data from Fast API
问题
我理解你的问题,你在开发一个学生考勤应用程序,使用React、Node和Express,同时使用FastAPI来获取数据。你已经成功地使用GET方法从API的getAllUser
端点获取数据并在表格中显示了它。然而,当尝试根据电子邮件地址获取数据时,出现了问题,没有显示任何错误。以下是你提供的不工作的代码部分:
import React, { useState, useEffect } from "react";
import axios from "axios";
export default function Users() {
const [users, setUsers] = useState([]);
const [email, setEmail] = useState("");
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const handleSearchClick = async () => {
try {
const response = await axios.get(`http://localhost:3001/getUser?email=${email}`);
setUsers(response.data);
setLoading(false);
} catch (error) {
setError("Failed to fetch data");
setLoading(false);
}
}
// ... 省略了其他部分,如渲染表格等
return (
<div>
<h1>Users</h1>
<div className="user-container">
<form className="search-user">
<input
type="text"
placeholder="email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button className="search-user-btn" onClick={handleSearchClick}>
Search
</button>
</form>
<table className="user-table">
{/* 表格渲染部分 */}
</table>
</div>
</div>
);
}
首先,请确保你已经导入了React和axios库,因为在你提供的代码中并没有导入声明。
接下来,请检查浏览器的开发者工具控制台,以查看是否有任何JavaScript错误消息。此外,确保FastAPI端点getUser
按预期工作并返回了正确的数据。
如果你仍然遇到问题,我建议在控制台中添加一些调试输出,以了解在何处出现问题。你可以在handleSearchClick
函数中添加console.log
语句,输出一些调试信息,以确定是否成功调用API端点以及是否收到预期的响应数据。
希望这可以帮助你解决问题。如果有进一步的疑问,请随时提问。
英文:
GUYS, I am currently developing a student attendance application using React, Node, and Express with Fast API and I used Get Method to fetch data from getAllUser from The API and saved it in a table as below it worked perfectly
and the code
import axios from "axios";
export default function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
async function fetchUsers() {
try {
const response = await axios.get('http://localhost:3001/getAllUsers');
setUsers(response.data);
setLoading(false);
} catch (error) {
setError("Failed to fetch data");
setLoading(false);
}
}
fetchUsers();
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>Users</h1>
<div className="user-container">
<table className="user-table">
<thead>
<tr>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>PHONE NUMBER</th>
<th>EMAIL</th>
<th>USER TYPE</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.phoneNumber}</td>
<td>{user.email}</td>
<td>{user.userType}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
but when I try to fetch data when add the email address it does not show any errors it won't display the output below the code i have provided the not working part
import React, {useState, useEffect} from "react";
import axios from "axios";
export default function Users() {
const [users, setUsers] = useState([]);
const [email, setEmail] = useState("");
const handleSearchClick = async () => {
try {
const response = await axios.get(`http://localhost:3001/getUser?email=${email}`);
setUsers(response.data);
setLoading(false);
} catch (error) {
setError("Failed to fetch data");
setLoading(false);
}
}
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error}</div>;
}
return (
<div>
<h1>Users</h1>
<div className="user-container">
<form className="search-user">
<input
type="text"
placeholder="email address"
value={email}
onChange={(e) => setEmail(e.target.value)}
/>
<button className="search-user-btn" onClick={handleSearchClick}>
Search
</button>
</form>
<table className="user-table">
<thead>
<tr>
<th>FIRST NAME</th>
<th>LAST NAME</th>
<th>PHONE NUMBER</th>
<th>EMAIL</th>
<th>USER TYPE</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>{user.firstName}</td>
<td>{user.lastName}</td>
<td>{user.phoneNumber}</td>
<td>{user.email}</td>
<td>{user.userType}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
below I have provided the server.js code
const express = require("express");
const axios = require("axios");
const cors = require("cors");
const {response} = require("express");
const app = express();
const port = 3001;
const FASTAPI_URL = 'http://174.138.23.76:8000';
app.use(express.json());
app.use(cors({origin: "http://localhost:3000", credentials: true,
methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
}));
// app.use((req, res, next) => {
// res.header("Access-Control-Allow-Origin", "*");
// res.header(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept"
// );
// next();
// });
app.post("/createUser", async (req, res) => {
try {
const formData = req.body;
// Make a POST request to the FastAPI backend with 'no-cors' mode
const response = await axios.post(`${FASTAPI_URL}/createUser`, formData);
console.log("User created:", response.data);
// Perform any necessary actions after successful user creation
res.json(response.data);
} catch (error) {
console.error("Error creating user:", error);
// Handle error condition
res.status(500).json({ error: "Failed to create user" });
}
});
app.post("/user/login", (req, res) => {
const {email, password} = req.body;
// Make a POST request to the FastAPI backend for login with 'no-cors' mode
axios
.post("http://174.138.23.76:8000/user/login", {email, password})
.then((response) => {
console.log("Login successful:", response.data);
// Perform any necessary actions after successful login
res.status(200).json(response.data);
})
.catch((error) => {
console.error("Error logging in:", error);
// Handle error condition
res.status(500).json({error: "Failed to log in"});
});
});
app.get("/getAllUsers", async (req, res) => {
try {
const url = `${FASTAPI_URL}/getAllUsers`;
const response = await axios.get(url);
res.json(response.data);
} catch (error) {
res.status(500).json({error: "Failed to fetch data"});
}
});
app.get("/getUser", async (req, res) => {
try {
const { email } = req.query; // Destructure the email from req.query directly
const url = `${FASTAPI_URL}/getUser?email=${email}`;
const response = await axios.get(url);
res.json(response.data);
} catch (error) {
res.status(500).json({ error: "Failed to fetch data" });
}
});
app.delete("/deleteUser", async (req, res) => {
const { email } = req.query;
try {
const url = `${FASTAPI_URL}/deleteUser?email=${email}`;
const response = await axios.delete(url);
res.json(response.data);
} catch (error) {
res.status(500).json({ error: "Failed to delete user" });
}
});
app.post("/updateUser", (req, res) => {
const updateData = req.body;
axios
.post('http://174.138.23.76:8000/updateUser', updateData)
.then((response) => {
console.log("User Updated:", response.data);
res.status(200).json(response.data);
})
.catch((error) => {
console.error("Error Updating user:", error);
res.status(500).json({error: "Failed to Update user"})
})
})
app.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`);
})
please help me to solve this problem
答案1
得分: 1
Edit Client Side:
const response = await axios.get(`http://localhost:3001/getUser/${email}`);
Add on Server Side:
app.get('/user/:email', async function (req, res) {
try {
const { email } = req.params;
const url = `${FASTAPI_URL}/getUser/${email}`; // 主要更改
const response = await axios.get(url);
res.json(response.data);
} catch (error) {
res.status(500).json({ error: "获取数据失败" });
}
})
英文:
Edit Client Side
const response = await axios.get(`http://localhost:3001/getUser/${email}`);
Add on Server Side
app.get('/user/:email', function (req, res) {
try {
const { email } = req.params.email;
const url = `${FASTAPI_URL}/getUser/${email}`; // main change
const response = await axios.get(url);
res.json(response.data);
} catch (error) {
res.status(500).json({ error: "Failed to fetch data" });
}
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论