Search code examples
node.jsreactjsmongodbnext.jsform-data

the form data is empty , can anyone explain why?


im trying to update data in mern stack application and i found that the formdata is empty and i wonder why !

i get all the value and pased them in function update to update the data and then i put them in form data , and i found that the form data is empty.

client side :

// file is empty not selected from the input 
const UpdateModule = async (annee, name, file, desc, id) => {
    const data = new FormData();
    data.append('annee', annee);
    data.append('name', name);
    data.append('desc', desc);
    if (file) {
      data.append('file', file);
    }
    console.log('FormData:', data); // here is empty
    // all the log below are not empty!
    console.log('annee:', annee);
    console.log('name:', name);
    console.log('desc:', desc);
    console.log('file:', file);
    const config = {
      headers: {
        'content-type': 'multipart/form-data',
        'accept': 'application/json'
      }
    };
    await axios.patch('http://localhost:5000/api/module/'+id,data,config).then(res => {
      // console.log(data)
      setLoadingUpdate(false)
      // setRefrech(refrech => refrech + 1)
      setSuccessUpdate(true)
      setErrorUpdate(false)
    }).catch(error => {
      console.log(error.message)
      console.log(error.response.data)
      setErrorUpdate(error.response.data)
      setSuccessUpdate(false)
      setLoadingUpdate(false)
    })
  }

server side :

const EditModule = async (req, res) => {
    try {
        const { id } = req.params
        const data = req.body
        const module = await Modules.findById(id)
        consol.log(data)
        console.log(module)
        if (!module) {
            return res.status(400).send('module not found')
        }
        const moduleUpdated = await Modules.findByIdAndUpdate(id, data, { new: true })
        console.log(moduleUpdated)
        res.status(201).json(moduleUpdated)
    } catch (error) {
        console.log(error.message)
    }
}

Solution

  • Actually, your formData is there. You cannot log it that way. Please, try this:

    for (var [key, value] of data.entries()) { 
        console.log(key, value);
    }