當我嘗試從特定用戶檢索帖子時出現此錯誤。獲取資料的代碼是正確的。不知道錯誤是從哪里來的。
從服務器端
客戶端

以下是單個帖子的代碼。
const UserPosts = () => {
const [user, setUser] = useState()
useEffect(() => {
const id = localStorage.getItem("userId");
const sendRequest = async () => {
const res = await axios.get(`/post/user/${id}`)
.catch(error => console.log(error));
const data = await res.data;
console.log(data)
return data;
}
sendRequest()
.then((data) => {
setUser(data.user)
console.log(data)
})
}, [])
return (
<div>
{user &&
user.posts.map((post, index) => (
<Post
id={post._id}
isUser={true}
key={index}
username={user.username}
caption={post.caption}
selectedFile={post.selectedFile}
createAt={post.createAt}
/>
)).reverse()}
</div>
)
}
export default UserPosts;
這是該路線的后控制器
export const getUserById = async (req, res) => {
const userId = req.params.id;
let userPosts;
try {
userPosts = await User.findById(userId).populate("posts");
} catch (error) {
console.log(error)
}
if (!userPosts) {
res.status(404).json({ message: "No Post Found" })
}
res.status(200).json({ user: userPosts })
}
uj5u.com熱心網友回復:
useEffect(() => {
const id = localStorage.getItem("userId");
const sendRequest = async () => {
const {data} = await axios.get(`http://localhost:backend-port/post/user/${id}`)
setUser(data.user)
}
sendRequest()
}, [])
請嘗試一下
uj5u.com熱心網友回復:
正如@Gavin 指出的那樣,您的問題是您以 404 的狀態回應,但隨后又退出了if另一個res.status呼叫。您不能像這樣多次發送狀態,并且必須重新構建邏輯以防止呼叫res.status兩次。兩個簡單可行的解決方案:
選項 1:return在錯誤處理塊中添加 a 以防止陷入非錯誤情況。
if (!userPosts) {
res.status(404).json({ message: "No Post Found" })
return;
}
res.status(200).json({ user: userPosts })
選項 2:使用else塊以對稱方式將錯誤情況與非錯誤情況分開。
if (!userPosts) {
res.status(404).json({ message: "No Post Found" })
} else {
res.status(200).json({ user: userPosts })
}
uj5u.com熱心網友回復:
我解決了這個問題。當用戶登錄時,我收到了錯誤的發布請求,該請求以錯誤的用戶 ID 結束,因此,未正確獲取發布資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/489835.html
標籤:javascript 节点.js 反应 表示
下一篇:洗掉輸入值時繼續驗證
