I\'m learning AngularJS and I want to know how to correctly wire it with Node with ExpressJS.
This is my controller:
app.controller(\'view1Ctrl\', fu
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/json
app.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
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-submit
in the form element like this:
<form ng-submit="sub()">