ExpressJS AngularJS POST ExpressJS AngularJS POST express express

ExpressJS AngularJS POST


The body-parser module for Node.js (Express) can get every data from your form post into a single object called req.body, so if you have a $scope object to define your form data you can inject directly that to have the same properties copied on req.body:

Angular:

app.controller('view1Ctrl', function($scope, $http) {    $scope.sub = function() {        $http.post('/view1',$scope.formData).        then(function(response) {            console.log("posted successfully");        }).catch(function(response) {            console.error("error in posting");        })    }});

HTML:

<form>      <input type="text" ng-model="formData.desc" placeholder="Enter desc" />      <input type="text" ng-model="formData.title" placeholder="Enter title" />      <button type="submit" class="btn btn-primary" ng-click="sub()">Submit</button></form>

Now when you submit it via $http.post('/view1', $scope.formData)you will get the same object, for example:

app.post('/view1', function(req, res) {    console.log(req.body.desc);    res.end();});

Instead having an ng-click on the submit button, you could also use ng-submitin the form element like this:

<form ng-submit="sub()">


First of all you should be aware of two global variable req and res.

when you hit post request req.body catches the request from http and body-parser extracts the raw content from post request.

app.post('/view1', function(req, res) { console.log(req.body.desc); res.end();});

before using it you must include

var bodyParser = require('body-parser');

and include middleware as

app.use(bodyParser.json()); // for parsing application/jsonapp.use(bodyParser.urlencoded({ extended: true })); // for parsing       application/x-www-form-urlencoded

more about middleware, req and res please refer to

http://expressjs.com/4x