Search code examples
angularjsnode.jsexpressmeanjsngresource

How to send data from angularjs controller to server(nodejs) controller in meanjs


Am trying to send my data from angular form to the server controller where I use those data to modify my json file, it seems in meanjs they use ngResource to communicate backend and FrontEnd data but I failed to comprehend how it works Below are the parts of my code which I judged may help to explain my problem.

machine.client.view.html

<section data-ng-controller=’MachineController’>
  <form class=’form-horizontal’ data-ng-submit=’create()’ novalidate>
    <fieldset>
      <div class="form-group">
        <label class="control-label" for="projectName">Name of the project</label>
        <div class="controls">
          <input type="text" class="form-control" id="projectName" data-ng-model="projectName" placeholder="my_first_project">
        </div>
        <div class="form-group">
          <input type="submit" class="btn btn-primary"></input>
        </div>
    </fieldset>
  </form>
</section>

machine.client.routes.js

(function() {
  'use strict';
  //Setting up route
  angular
    .module('machine')
    .config(routeConfig);

  routeConfig.$inject = ['$stateProvider'];

  function routeConfig($stateProvider) {
    // Machine state routing
    $stateProvider
      .state('machine', {
        url: '/machine',
        templateUrl: 'modules/machine/client/views/machine.client.view.html',
        controller: 'MachineController',
        controllerAs: 'vm'
      });
  }
})();

machine.client.controller.js

(function() {
  'use strict';

  angular
    .module('machine')
    .controller('MachineController', MachineController);

  MachineController.$inject = ['$scope'];

  function MachineController($scope) {
    var vm = this;


    // Machine controller logic
    $scope.create = function() {
      console.log("Testing the functionalites");
      console.log(this.projectName);
    };
    init();

    function init() {}
  }
})();

machine.server.controller.js

'use strict';
/**
 * Module dependencies.
 */
require('require-xml');
var path = require('path'),
  mongoose = require('mongoose'),
  initialJsonFile = require('../resources/config.json'),
  finalJsonFile = './modules/machine/server/config/config1.json',
  updatedJson = require('../config/config1.json'),
  js2xmlparser = require('js2xmlparser'),
  jsonfile = require('jsonfile'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');
/**
 * Converting xml to json
 */
exports.updatingJsonConfig = function(req, res) {

  //I do need here to get data from angular form the string 'testing      description' it was only used to test the modifications
  initialJsonFile.project.projectName = 'testing description';

};

machine.server.routes.js

'use strict';
var machine = require('../controllers/machine.server.controller');
module.exports = function(app) {
  app.route('/testing').get(machine.updatingJsonConfig);
};

NB : I used one input in the form to only explain the problem,but it is a form of multiple fields


Solution

  • In the MEAN stack you use Express on the server side (Node) to set up a HTTP server, and your Angular front-end application communicates with the server through the HTTP protocol. It's not included in your posted code, but I assume there is a http server set up in your server side code. something like

    var server = http.createServer(app);
    server.listen(8080);
    

    On your local computer, you will be able to access the http server set up like this on localhost:8080.

    app.route('/testing').get(machine.updatingJsonConfig)

    This line defines a route handler, in this context it means "when you hit localhost:8080/testing with a HTTP GET REQUEST execute machine.updatingJsonConfig.

    updatingJsonConfig is an express middleware function, that has access to the req and res objects. If you want to respond to the HTTP request you need to call res.send() at the end of your updatingJsonConfig function with whatever response you want to send as an argument.

    Then on the client side you need to make a http request to your server and process the response. The simplest way of doing this is using the $http service like:

    $http.get('/localhost:8080/testing')
    .then(function(response) {
     // do something with the response
    });
    

    ngResource makes the same HTTP request, you don't really need it here.

    So res.send() on the server, $http.get in the client.

    EDIT:

    In order to send form data through HTTP you need to make a POST request with $http.post instead of $http.get. GET requests don't have a body.

    On the server side you need to change your route to handle POST requests

    app.route('/testing').post(machine.updatingJsonConfig)

    You'll also need to include the body-parser module in express, and you'll have a req.body available.