无法从Fast API获取数据。

huangapple go评论82阅读模式
英文:

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 无法从Fast API获取数据。

and the code

  import axios from &quot;axios&quot;;
export default function Users() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() =&gt; {
async function fetchUsers() {
try {
const response = await axios.get(&#39;http://localhost:3001/getAllUsers&#39;);
setUsers(response.data);
setLoading(false);
} catch (error) {
setError(&quot;Failed to fetch data&quot;);
setLoading(false);
}
}
fetchUsers();
}, []);  
if (loading) {
return &lt;div&gt;Loading...&lt;/div&gt;;
}
if (error) {
return &lt;div&gt;Error: {error}&lt;/div&gt;;
}
return (
&lt;div&gt;
&lt;h1&gt;Users&lt;/h1&gt;
&lt;div className=&quot;user-container&quot;&gt;
&lt;table className=&quot;user-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;FIRST NAME&lt;/th&gt;
&lt;th&gt;LAST NAME&lt;/th&gt;
&lt;th&gt;PHONE NUMBER&lt;/th&gt;
&lt;th&gt;EMAIL&lt;/th&gt;
&lt;th&gt;USER TYPE&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{users.map((user) =&gt; (
&lt;tr key={user.id}&gt;
&lt;td&gt;{user.firstName}&lt;/td&gt;
&lt;td&gt;{user.lastName}&lt;/td&gt;
&lt;td&gt;{user.phoneNumber}&lt;/td&gt;
&lt;td&gt;{user.email}&lt;/td&gt;
&lt;td&gt;{user.userType}&lt;/td&gt;
&lt;/tr&gt;
))}
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
);
}

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 &quot;react&quot;;
import axios from &quot;axios&quot;;
export default function Users() {
const [users, setUsers] = useState([]);
const [email, setEmail] = useState(&quot;&quot;);
const handleSearchClick = async () =&gt; {
try {
const response = await axios.get(`http://localhost:3001/getUser?email=${email}`);
setUsers(response.data);
setLoading(false);
} catch (error) {
setError(&quot;Failed to fetch data&quot;);
setLoading(false);
}
}
if (loading) {
return &lt;div&gt;Loading...&lt;/div&gt;;
}
if (error) {
return &lt;div&gt;Error: {error}&lt;/div&gt;;
}
return (
&lt;div&gt;
&lt;h1&gt;Users&lt;/h1&gt;
&lt;div className=&quot;user-container&quot;&gt;
&lt;form className=&quot;search-user&quot;&gt;
&lt;input
type=&quot;text&quot;
placeholder=&quot;email address&quot;
value={email}
onChange={(e) =&gt; setEmail(e.target.value)}
/&gt;
&lt;button className=&quot;search-user-btn&quot; onClick={handleSearchClick}&gt;
Search
&lt;/button&gt;
&lt;/form&gt;
&lt;table className=&quot;user-table&quot;&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;FIRST NAME&lt;/th&gt;
&lt;th&gt;LAST NAME&lt;/th&gt;
&lt;th&gt;PHONE NUMBER&lt;/th&gt;
&lt;th&gt;EMAIL&lt;/th&gt;
&lt;th&gt;USER TYPE&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{users.map((user) =&gt; (
&lt;tr key={user.id}&gt;
&lt;td&gt;{user.firstName}&lt;/td&gt;
&lt;td&gt;{user.lastName}&lt;/td&gt;
&lt;td&gt;{user.phoneNumber}&lt;/td&gt;
&lt;td&gt;{user.email}&lt;/td&gt;
&lt;td&gt;{user.userType}&lt;/td&gt;
&lt;/tr&gt;
))}
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/div&gt;
&lt;/div&gt;
);
}

below I have provided the server.js code

const express = require(&quot;express&quot;);
const axios = require(&quot;axios&quot;);
const cors = require(&quot;cors&quot;);
const {response} = require(&quot;express&quot;);
const app = express();
const port = 3001;
const FASTAPI_URL = &#39;http://174.138.23.76:8000&#39;;
app.use(express.json());
app.use(cors({origin: &quot;http://localhost:3000&quot;, credentials: true,
methods: [&#39;GET&#39;, &#39;PUT&#39;, &#39;POST&#39;, &#39;DELETE&#39;, &#39;OPTIONS&#39;],
}));
// app.use((req, res, next) =&gt; {
//     res.header(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);
//     res.header(
//         &quot;Access-Control-Allow-Headers&quot;,
//         &quot;Origin, X-Requested-With, Content-Type, Accept&quot;
//     );
//     next();
// });
app.post(&quot;/createUser&quot;, async (req, res) =&gt; {
try {
const formData = req.body;
// Make a POST request to the FastAPI backend with &#39;no-cors&#39; mode
const response = await axios.post(`${FASTAPI_URL}/createUser`, formData);
console.log(&quot;User created:&quot;, response.data);
// Perform any necessary actions after successful user creation
res.json(response.data);
} catch (error) {
console.error(&quot;Error creating user:&quot;, error);
// Handle error condition
res.status(500).json({ error: &quot;Failed to create user&quot; });
}
});
app.post(&quot;/user/login&quot;, (req, res) =&gt; {
const {email, password} = req.body;
// Make a POST request to the FastAPI backend for login with &#39;no-cors&#39; mode
axios
.post(&quot;http://174.138.23.76:8000/user/login&quot;, {email, password})
.then((response) =&gt; {
console.log(&quot;Login successful:&quot;, response.data);
// Perform any necessary actions after successful login
res.status(200).json(response.data);
})
.catch((error) =&gt; {
console.error(&quot;Error logging in:&quot;, error);
// Handle error condition
res.status(500).json({error: &quot;Failed to log in&quot;});
});
});
app.get(&quot;/getAllUsers&quot;, async (req, res) =&gt; {
try {
const url = `${FASTAPI_URL}/getAllUsers`;
const response = await axios.get(url);
res.json(response.data);
} catch (error) {
res.status(500).json({error: &quot;Failed to fetch data&quot;});
}
});
app.get(&quot;/getUser&quot;, async (req, res) =&gt; {
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: &quot;Failed to fetch data&quot; });
}
});
app.delete(&quot;/deleteUser&quot;, async (req, res) =&gt; {
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: &quot;Failed to delete user&quot; });
}
});
app.post(&quot;/updateUser&quot;, (req, res) =&gt; {
const updateData = req.body;
axios
.post(&#39;http://174.138.23.76:8000/updateUser&#39;, updateData)
.then((response) =&gt; {
console.log(&quot;User Updated:&quot;, response.data);
res.status(200).json(response.data);
})
.catch((error) =&gt; {
console.error(&quot;Error Updating user:&quot;, error);
res.status(500).json({error: &quot;Failed to Update user&quot;})
})
})
app.listen(port, () =&gt; {
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(&#39;/user/:email&#39;, 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: &quot;Failed to fetch data&quot; });
}
}) 

huangapple
  • 本文由 发表于 2023年7月28日 01:37:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76782224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定