Home > Blockchain >  Node does not receive React's POST request
Node does not receive React's POST request

Time:02-01

Here's my React code in posting:

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)
        })

}

And for my Node/Express backend:

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})
    }
})

However, req.body is empty on my backend. And on React, it says "Successfully Posted!" and its status is 200 (so there were no errors). It just doesn't save and it doesn't see the data from that was sent from React as well.

Any ideas? Thank you!

BTW: On React, all the fields (nickname, title, content) are completely working on the frontend.

CodePudding user response:

This appears to be failing for three separate reasons, each of which would independently cause the symptoms you are describing.

You are passing the wrong variable

  1. You collect the data in data
  2. You call setThePost(data) (which I assume is associated with a useState)
  3. You pass thepost to the body but thepost is the previous value of the state, and you won't get the new value until the component is re-rendered, but which time it is too late.

Don't use the state for this. Just use the data immediately

You are passing fetch an object

Look at the MDN docs:

Any body that you want to add to your request: this can be a Blob, BufferSource, FormData, URLSearchParams, USVString, or ReadableStream object

A plain object is none of those things.

You should create a suitable object with either URLSearchParams or FormData depending on what format the server is expecting the data in. You might also want to encode it as JSON (and set the right Content-Type header).

The server has no body parsing middleware

See the express docs:

By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

You need to include body parsing middleware that matches the type of data you picked in when you replaced the object with something suitable in the previous section of this answer.


The combination of URLSearchParams and express.urlencoded() would probably be most suitable.

CodePudding user response:

You are fetching from url : http://localhost:3001/posts in your react code but in node js you are using router.post('/', async(req,res) but you should use router.post('/post', async(req,res) instead.

See in router.post you should add posts same as you are using for fetching.

Also after correction try to do hard reload the page or try to test on incognito mode on getting empty req.body.

  •  Tags:  
  • Related