node.js - ExpressJS AngularJS POST -
i'm learning angularjs , want know how correctly wire node expressjs.
this controller:
app.controller('view1ctrl', function($scope, $http) { $scope.sub = function(desc) { console.log(desc); $http.post('/view1', desc). then(function(response) { console.log("posted successfully"); }).catch(function(response) { console.error("error in posting"); }) } });
and server.js:
app.post('/view1', function(req, res) { console.log(res.desc); res.end(); });
i have not used body-parser. don't how body-parser used form values html when using function in controller. values got html on clicking submit when using body-parser or values got function on passing form values arguments. please tell me how done .
edit: html:
<form> <input type="text" ng-model="desc" placeholder="enter desc" /> <button class="btn btn-primary" ng-click="sub(desc)">submit</button> </form>
edit 2: full server.js code:
var express = require('express'), http = require('http'), path = require('path'), bodyparser= require('body-parser'); var app = express(); app.set('port', 3000); app.use(express.static(path.normalize(__dirname + '/'))); app.use(bodyparser.json()); // parsing application/json app.use(bodyparser.urlencoded({ extended: true })); // parsing application/x-www-form-urlencoded app.get('/main', function(req, res) { var name = 'mynamefromserver'; res.send(name); }); app.post('/view1', function(req, res) { console.log(res.body.desc); res.end(); }); http.createserver(app).listen(app.get('port'), function() { console.log('express server listening on port ' + app.get('port')); });
edit 3: edited controller app.js
app.controller('view1ctrl', function($scope, $http) { $scope.sub = function() { console.log($scope.formdata); $http.post('/view1', $scope.formdata). success(function(data) { console.log("posted successfully"); }).error(function(data) { console.error("error in posting"); }) }; });
the body-parser module node.js (express) can every data form post single object called req.body
, if have $scope
object define form data can inject directly have 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 submit via $http.post('/view1', $scope.formdata)
you same object, example:
app.post('/view1', function(req, res) { console.log(req.body.desc); res.end(); });
instead having ng-click on submit button, use ng-submit
in form element this:
<form ng-submit="sub()">
Comments
Post a Comment