[英]Cannot send request from client side to server side in a MERN project
在進行個人項目時,一切都很好。 但不幸的是我遇到了一個特殊的問題,因為我無法找出這個問題背后的原因。 請讓我描述一下問題。 這是我試圖從前端向其發送請求的后端點。
router.get("/profile/:username", async (req, res) => {
try {
const user = await User.findOne({ username: req.params.username })
const posts = await Post.find({ userId: user._id })
req.status(200).json(posts)
} catch (err) {
res.status(500).json(err);
}
})
這是我嘗試發送請求的前端點
useEffect(() => {
const fetchPosts = async () => {
const res = username
? await axios.get("posts/profile/"+username)
: await axios.get("posts/timeline/638b46766863c22bd1c7e242")
setPosts(res.data)
}
fetchPosts()
}, [username])
username
來自另一個我寫的文件<Feed username={"Shibly"}/>
。 我想從localhost:3000/api/posts/profile/Shibly
獲取數據,但出現404
錯誤。
請注意, await axios.get("posts/timeline/638b46766863c22bd1c7e242")
工作正常。
請有人幫助我。 提前致謝。
首先,您正在從我從您的網絡選項卡中看到的前端訪問這個 API 端點。 請檢查此 API 端點在后端是否存在。
http://localhost:3000/profile/posts/profile/Shibly
此外,您可以將這種方式用於前端的動態路由
useEffect(() => {
const fetchPosts = async () => {
const res = username
? await axios.get(`posts/profile/:${username}`)
: await axios.get("posts/timeline/638b46766863c22bd1c7e242")
setPosts(res.data)
}
fetchPosts()
}, [username])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.