how to properly send and receive form data in an angular/node application

1.1k views Asked by At

I'm writing an app based on mean.js boiler plate

I have a form in my angular view, which need to send some formData:

 <form name="form" ng-submit="postUpdate()">
                <div class="form-group">
                    <fieldset>
                        <legend><strong>Salesforce Opportunity</strong> </legend>
                        <div class="col-sm-6">
                            <label for="opportunityId">Opportunity ID</label>
                            <input id="kw" name="opportunityId" type="text" placeholder="kw" class="form-control" ng-model="kwRequired"/>
......

In my angular controller, I have this:

$scope.postUpdate = function(){
            var posturl = '/salesforce_update';
            console.log('kwRequired  ' + $scope.kwRequired);
            var postData = {kw: $scope.kwRequired};
            $http.post(posturl,postData);
        }

Then, in my server node/express code, I have this handler:

....

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


app.post('/salesforce_update', function(req, res){
        console.log('Salesforce update Request Received');
        console.log('_parsedUrl.query:  ' + req.body.kw);
    });

I do get the request across to the server side just fine, but, upon examination, the request body is empty.

What am I missing?

1

There are 1 answers

1
Jossef Harush Kadouri On BEST ANSWER

You need to use angular.toJson method like this:

$scope.postUpdate = function(){
    console.log('kwRequired  ' + $scope.kwRequired);
    var postData = {kw: $scope.kwRequired};
    var json = angular.toJson(postData); 
    $http.post('/salesforce_update', json);
}

Also make sure to define app.use(bodyParser.json()); before the definition of app.post('/salesforce_update', function ....