[英]Node does not receive React's POST request
這是我發布的 React 代碼:
const [nickname, setNickname] = useState('')
const [title, setTitle] = useState('')
const [content, setContent] = useState('')
const [agree, setAgree] = useState(false)
const [thepost, setThePost] = useState({})
const DoSubmit = async () => {
setHasAlert(false)
if (nickname == '' || nickname == null) {
setAlertContent("Please enter a Nickname!")
setHasAlert(true)
return
}
if (title == '' || title == null) {
setAlertContent("Please enter a Title!")
setHasAlert(true)
return
}
if (content == '' || content == null) {
setAlertContent("Cannot post an empty content!")
setHasAlert(true)
return
}
if (agree == false) {
setAlertContent("Please agree to the post rules!")
setHasAlert(true)
return
}
const data = {
title: title,
nickname: nickname,
content: content
}
setThePost(data)
await fetch('http://localhost:3001/posts', {
method: "POST",
body: thepost
})
.then(res => {
setIsError(false)
setAlertContent("Posted Successfully!")
setHasAlert(true)
console.log(res)
})
.catch(err => {
setAlertContent(err.message)
setHasAlert(true)
})
}
對於我的 Node/Express 后端:
router.post('/', async(req,res) => {
const post = new Post({
nickname: req.body.nickname,
title: req.body.title,
content: req.body.content
})
console.log(req.body)
try {
const savedPost = await post.save()
res.json(savedPost)
console.log(savedPost)
}
catch(err){
res.json({message:err})
}
})
但是, req.body
在我的后端是空的。 在 React 上,它顯示“成功發布!” 並且它的狀態是200
(所以沒有錯誤)。 它只是不保存,也看不到從 React 發送的數據。
有任何想法嗎? 謝謝!
順便說一句:在 React 上,所有字段(昵稱、標題、內容)都完全在前端工作。
更新
我在反應中使用/posts
但在節點中使用/
因為我已經在節點的主app.js
上使用了中間件,如下所示:
const postsRoute = require('./routers/posts')
app.use('/posts', postsRoute)
我有一個獲取所有帖子的 React 頁面:
const fetchData = async () => {
const data = await fetch('http://localhost:3001/posts')
const dataPost = await data.json()
setAllPosts(dataPost)
}
一切正常。
這似乎因三個不同的原因而失敗,每個原因都會獨立地導致您所描述的症狀。
data
setThePost(data)
來更新 statethepost
傳給body
問題是post是thepost
的先前值。 在重新渲染組件並創建新的DoSubmit
function 之前,您將無法獲得新值,但為時已晚 - 您正在使用現有的DoSubmit
function。
不要為此使用 state。 立即使用數據。
fetch
object查看MDN 文檔:
您要添加到請求中的任何主體:這可以是 Blob、BufferSource、FormData、URLSearchParams、USVString 或 ReadableStream object
普通的 object 不是這些東西。
您應該使用URLSearchParams
或FormData
創建合適的 object,具體取決於服務器期望數據的格式。您可能還希望將其編碼為 JSON(並設置正確的 Content-Type 標頭)。
請參閱快速文檔:
默認情況下,它是未定義的,並且在您使用諸如 express.json() 或 express.urlencoded() 之類的正文解析中間件時填充。
您需要包含與您在將 object 替換為本答案上一部分中合適的內容時選擇的數據類型相匹配的正文解析中間件。
URLSearchParams
和express.urlencoded()
的組合可能是最合適的。
您在反應代碼中從 url: http://localhost:3001/posts 獲取,但在節點 js 中您使用的是 router.post('/', async(req,res) 但您應該使用 router.post('/ post', async(req,res) 代替。
請參閱 router.post 您應該添加與用於獲取相同的帖子。
同樣在更正后嘗試重新加載頁面或嘗試在隱身模式下測試獲取空的req.body。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.