简体   繁体   中英

React FormData() shows correct payload but getting 400 bad request

I am using a call to new FormData() . The network tab shows that the payload is correct. In the console I am getting the following error:

{message: "Blog validation failed: title: Path `title` is required., postBody: Path `postBody` is required."}

However, in the network tab it's showing that the title and postBody fields are being sent:

Network tab headers output

The server is written with nodejs and is using mongodb. All the routes are working on the backend when testing. Data is posted fine when testing it using a .rest file, but I'm still new to node so I'll post my handler for the post route as well:

router.post('/', async (req, res) => {
    const blogPost = new Blog({
        title: req.body.title,
        author: req.body.author,
        postBody: req.body.postBody,
        postDate: req.body.postDate
    })
    try {
        const newPost = await blogPost.save();
        res.status(201).json(newPost);
    } catch (err) {
        res.status(400).json({ message: err.message })
    }
})

Like I said, when making calls to this route directly using a .rest file everything works fine.

Here's my form submit handler on the frontend:

handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.target);

    console.log(event.target);
    console.log(data);
    console.log(event.target.postBody.value);

    fetch('http://localhost:4000/blog', {
      method: 'POST',
      mode: 'cors',
      body: data
    })
    .then(res => res.json())
    .then(err => console.error(err))
  }

Maybe I misunderstand the usage of new FormData() ?

Ok so when I added body-parser I was still getting the same error. Not sure what I'm doing wrong tbh. However, in the interest of my own time in dealing with this I came up with another solution. I am accepting json in my node app via app.use(express.json())

In the end, I just needed to send headers with the content type and I'm no longer using FormData() . My updated form submit handler (working):

handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.target);
    const body = event.target.postBody.value;
    const postTitle = event.target.title.value;

    console.log(event.target);
    console.log(data);
    console.log(event.target.postBody.value);

    fetch('http://localhost:4000/blog', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      mode: 'cors',
      body: JSON.stringify({
        title: postTitle,
        postBody: body
      })
    })
    .then(res => res.json())
    .then(err => console.error(err))
  }

This works for me and it's what I'm going with for now so that I can move forward, however, it still does not answer why the formData() method I tried previously was not working, even after using body-parser, as was suggested here.

You need body parser in your node app

 const bodyParser = require('body-parser')

 app.use(
     bodyParser.urlencoded({
         extended: true
     })
 )

app.use(bodyParser.json())

Also, make sure you receive your data. Try logging your data.

You need install body-parser , and use this dependency in the app.js (or the name that you using)

Copy the next snippet in the top of the file:

const bodyParser = require('body-parser');
const express = require('express');
const app = express();

Then, copy the next snippet in the file's body;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

With this, you route will's done!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM