Saurabh Sharma Saurabh Sharma - 2 months ago 5
Javascript Question

User Data is not inserting into mongodb using Node API

I am creating a Restful API on Node.js and storing data into Mongodb. and working on user registration API.

app.js

apiRoutes.post('/signup', function(req, res) {
if (!req.body.name || !req.body.password) {
res.json({success: false, msg: 'Please pass Name and Password.'});
} else {
var newUser = new User({
name:req.body.name,
password:req.body.password
});
console.log(req.body.name);
// save the user
newUser.save(function(err, data) {
if (err) {
return res.json({success: false, msg: 'Username already exists.'});
}else{
console.log(data);
res.json({success: true, msg: 'Successful created new user.'});}
});
}
});


Consuming API using Angular.js

//factory for user register
app.factory('RegistrationFactory', function($resource){
return $resource('/api/signup/:id',{id:'@_id'},{update:{method:'PUT'}});
});

//controller for registration
app.controller('registerCtrl', function($scope, RegistrationFactory, $location){
$scope.regUser=new RegistrationFactory();
$scope.register=function(){
console.log($scope.newUser);
$scope.regUser.$save(function(){
console.log("User Registerd");
});

} ;

})


register.html

<div class="post" ng-controller="registerCtrl">
<form method="post">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" ng-model="newUser.name" />
</div>
<div class="form-group">
<label>Password</label>
<input type="text" class="form-control" name="password" ng-model="newUser.password"/>
</div>
<div class="form-group">
<button class="btn btn-success" ng-click="register()">Register</button>
</div>
</form>
</div>


So, My problem is that, this API is working fine on
POSTMAN
but its not working on my HTML form. Please review my code. Whenever I click on Register button its seems like that on button click API is not hitting. nothing is happening.
Please review my code and suggest me solution.

Thanks.

raj raj
Answer

from angular controller you are not passing the newUser object to $resource or regUser change the controller code to below

 //controller for registration
app.controller('registerCtrl', function($scope, RegistrationFactory, $location){
$scope.register=function(){
    console.log($scope.newUser);
    $scope.regUser=new RegistrationFactory($scope.newUser);
    $scope.regUser.$save(function(){
                        console.log("User Registerd");
                        });

    } ;

})