ExpressJS AngularJS POST

前端 未结 2 1476
囚心锁ツ
囚心锁ツ 2020-12-16 20:18

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         


        
2条回答
  •  忘掉有多难
    2020-12-16 21:03

    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:

    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:

提交回复
热议问题