angularjsmongoosemean-stackangularjs-resource

How to post some data and get results using MEAN stack and ngResource


I am working on a application and I am using MEAN stack as technology. In AngularJS, I am using ngResource to CRUD operations. Can any one suggest how to send username and password to server and get response back to check if the credentials are valid. I need help in ngResource and mongoose code. Thanks.


Solution

  • Check out the mean.js boilerplate: https://github.com/meanjs/mean

    You'll see how they do it pretty quickly:

    moduleName.client.controller.js will make an http call, using the injected http. Here is an example of the call being made from /modules/users/client/controllers/authentication.client.controller.js (with some edits to the code to make it easier to see what you're looking for):

    AuthenticationController.$inject = ['$scope', '$state', '$http', 'Authentication'];
    
    function AuthenticationController($scope, $state, $http, Authentication, ) {
      ...
      vm.authentication = Authentication;
    
      $http.post('/api/auth/signup', vm.credentials).success(function (response) {
        // If successful we assign the response to the global user model
        vm.authentication.user = response;
    
      }).error(function (response) {
        vm.error = response.message;
      });
    }
    

    Now, this call is posted to '/api/auth/signup'. The file that handles this route is located in /modules/users/server/routes/auth.server.routes.js:

    modules.exports = function(app) {
      var users = require('../controllers/users.server.controller');
      ...
      app.route('/api/auth/signup').post(users.signup);
    }
    

    As you can see, the route (the url) matches the one you called from the client controller. As that $http call from the controller was a $http.post(), the route entry must match. You can see that it does above. The parameter users.signup passed above refers to a function in yet another file: /modules/users/server/controllers/users/users.authentication.server.controller.js. This is your main controller for the authentication part of the users module. Now, within this file we can see the signup function is exported:

    /* note: there are global variables here, see below */
    exports.signup = function (req, res) {
      // For security measurement we remove the roles from the req.body object
      delete req.body.roles;
    
      // Init user and add missing fields
      var user = new User(req.body);
      user.provider = 'local';
      user.displayName = user.firstName + ' ' + user.lastName;
    
      // Then save the user
      user.save(function (err) {
        if (err) {
          return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
          });
        } else {
          // Remove sensitive data before login
          user.password = undefined;
          user.salt = undefined;
    
          req.login(user, function (err) {
            if (err) {
              res.status(400).send(err);
            } else {
              res.json(user);
            }
          });
       }
     });
    };
    

    Now, a lot is going on here, but we can break it down.

    The req variable is the post request as passed by $http. The res variable is the response the client expects to receive back. Notice how vm.credentials was passed in $http.post('/api/auth/signup/', vm.credentials)? This is bound to req.body and may be accessed by your server controller from that.

    So in this example, the req.body is the required data to create a new user on the server. This is done using mongoose, which has a schema called User. Access this by declaring globals at the top of your controller:

    var mongoose = require('mongoose'),
      User = mongoose.model('User');
    

    You can see that a new user is instantiated above. It is saved via the mongoose call .save().

    Lastly, your server functions should response to the client's request using the res variable passed to the function. See how once the user is created successfully, the function calls

    res.jsonp(user);
    

    This is success() to the client, which accepts the response and binds it to a local variable vm.authentication.user

    Hope this helps!