skip to Main Content

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

2

Answers


  1. It looks like you’re using express, which means you should specify the appropriate body-parser middleware for the request body to contain the body.

    Add a body parser middleware before you define your routes

    app.use(express.urlencoded());
    
    Login or Signup to reply.
  2. Actually your formdata is their. You cannot log that way. Please, try this: :

    for (var [key, value] of data.entries()) { 
        console.log(key, value);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search