9

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', 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 this is my server.js:

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

I have not used body-parser. I don't get how body-parser is used to get the form values from the html when I am using a function in controller. Does the values got from the html on clicking submit when using body-parser or does the values are got from the function on which I am passing the form values as arguments. Please tell me how it is done .

EDIT: this is my 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()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for 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");
        })
    };
});

2 Answers 2

27

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()">
Sign up to request clarification or add additional context in comments.

9 Comments

What about the ng-click of the button ? should it pass the desc once again or should I just have to call it with out passing anything ?
You don't need it, you have the $scope I'm updating the answer.
After all the modifications , it says TypeError: Cannot read property 'desc' of undefined..
I actually get that error in the node server.! It says desc is undefined.
Do a console.log(req.body)
|
8

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

5 Comments

So in my html , there is no need for me to pass the desc variable ? should I just call the sub() ?
of course angular's two-way data-binding does it for you. when you define ng-model= 'desc' in view you can use it in your controller with $scope.desc.
yeah no need to pass it, $scope object contains all the scope variable within the territory you defined your controller.
and does req.body contain only the values inside that particular form ? also can you add the controller in your answer . I still don't get it .
app.use(bodyParser.json()) was it for me! Oh man that was frustrating.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.