mayank bisht
mayank bisht

Reputation: 618

Not able to get form-data sent from angular to node server

I am sending form-data along with image-data.
But I am unable to get data on the node server when sent inside FormData.

I could see data on the angular controller on console.log.

angular code:

$scope.saveInfo = function(){
  var formData = new FormData;
  console.log('Update function');
  for(key in $scope.seller){
    formData.append(key, $scope.seller[key]);
  }
  console.log(key, $scope.seller);
  var file = $('#file')[0].files[0];
  formData.append('image', file);

  $http.put('/api/seller/businessInformation', formData, {
    transformRequest: angular.Identity,
    headers: {
      'Content-type': undefined
    }
  }).then(function(res){

  });
}

Node.Js: I could see image data on console.log(req.files);,
but console.log(req.body); prints [object object].

Upvotes: 6

Views: 1726

Answers (3)

mayank bisht
mayank bisht

Reputation: 618

The problem is with the ng-model data binding.
I was binding data like this: 'seller.a.b.c'
Instead I did seller.a and it worked.

Upvotes: -4

Sajeetharan
Sajeetharan

Reputation: 222592

The best way to tackle this issue is

(i) JSON.stirngify(req.body) in your code.

(ii) See what is the data getting printed, then based on the output you can use req.body.whateverField

EDIT

You can access FormData as,

console.log(req.files.file.name);

and to access FormData you can use

var a = JSON.parse(req.body.name);
console.log(a);

Upvotes: 5

Supraj V
Supraj V

Reputation: 977

req.body is an object. If your form-data contains name and age. then you can get those values in node like below

req.body.name
req.body.age

Upvotes: 0

Related Questions