1

I am trying to sent my form data to node js and retrieve at there.But I am failed to do it with form data object.

handleSubmit(data) {
    console.log(data);
    const forms=new FormData();
    forms.append('fname','pranab');
    let promise=fetch('http://localhost:8080/reactTest', {
        method:'POST',
        mode:'CORS',
        body:JSON.stringify(forms),
        headers:{
                'Content-Type':'application/json',
                'Accept':'application/json'
        }
    }).then(res =>res.json()).then(result => console.log(result))
}

in the above code I am sending form data object to the serve side.At the server side I am trying to retrieve it using below code.

app.post('/reactTest',function(req,res) {
        var contents=req.body;
        console.log(contents);
        return res.send({status:'working'});
    })

but it displays nothing in the console.What the issue here is?

output is

titech@titech-System-Product-Name:/var/www/html/nodejs$ node index.js
port listening on 8080
{}

when i trying to console it with 'req.body.fname' it gives 'undefined' as output in place of '{}'.

Janak
  • 4,986
  • 4
  • 27
  • 45
Pranab V V
  • 1,386
  • 5
  • 27
  • 53

2 Answers2

0

Looks like you need some function to convert formData to JSON. Like this one:

function formData2Json(formData){
  let ret={};
  for(let pair of formData.entries()) {
   let val=ret[pair[0]];
   if (!val) {
    ret[pair[0]]=pair[1];
   }
   else {
     if (Array.isArray(val)) {
       val.push(pair[1]);
     }
     else {
       ret[pair[0]]=[val,pair[1]];
     }
   }
  }
  return ret;
}

and than replace body:JSON.stringify(forms) with body:JSON.stringify(formData2Json(forms))

Vasyl Moskalov
  • 4,242
  • 3
  • 20
  • 28
0

try this it may help

var bodyFormData = new FormData();
bodyFormData.set('userName', 'Fred');

axios({
    method: 'post',
    url: 'myurl',
    data: bodyFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
})
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });
Srikanth Gowda
  • 6,163
  • 7
  • 19
  • 34