【问题标题】:Node does not receive React's POST requestNode 没有收到 React 的 POST 请求
【发布时间】:2022-02-01 02:00:43
【问题描述】:

这是我发布的 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)
}

一切正常。

【问题讨论】:

    标签: javascript node.js reactjs mongodb express


    【解决方案1】:

    这似乎因 三个不同的原因而失败,每个原因都会独立地导致您所描述的症状。

    你传递了错误的变量

    1. 您在data 中收集数据
    2. 你调用setThePost(data)更新状态
    3. 您将thepost 传递给body

    问题在于thepost 是状态的previous 值。在重新渲染组件并创建新的 DoSubmit 函数之前,您不会获得新值,但为时已晚 - 您正在使用现有的 DoSubmit 函数。

    不要为此使用状态。立即使用数据。

    您正在传递 fetch 一个对象

    the MDN docs

    您要添加到请求中的任何正文:这可以是 Blob、BufferSource、FormData、URLSearchParams、USVString 或 ReadableStream 对象

    一个普通的对象不是这些东西。

    您应该使用URLSearchParamsFormData 创建一个合适的对象,具体取决于服务器期望数据的格式。您可能还希望将其编码为 JSON(并设置正确的 Content-Type 标头)。

    服务器没有body解析中间件

    the express docs:

    默认情况下,它是未定义的,并在您使用诸如 express.json() 或 express.urlencoded() 之类的正文解析中间件时填充。

    您需要包含正文解析中间件,该中间件与您在将对象替换为本答案上一部分中合适的对象时选择的数据类型相匹配。


    URLSearchParamsexpress.urlencoded() 的组合可能是最合适的。

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    您在反应代码中从 url 获取:http://localhost:3001/posts 但在节点 js 中您使用的是 router.post('/', async(req,res) 但您应该使用 router.post ('/post', async(req,res) 代替。

    在 router.post 中看到,您应该添加与用于获取相同的帖子。

    同样在更正后尝试重新加载页面或尝试在隐身模式下测试获取空的 req.body。

    【讨论】:

    • 由于代码有router.post('/',它可能位于安装在/posts 的Express Router 上,因此URL 会匹配。 (即不是app.post('/'
    • 哦,我的错,就是这样,因为我已经在 node.js 的主 app.js 上添加了前缀。我会更新我的问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-03-17
    • 1970-01-01
    • 2019-07-23
    • 2018-02-07
    • 2015-09-18
    • 2022-01-25
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多