如何将数据从angularjs控制器发送到meanjs中的服务器(nodejs)控制器

时间:2021-12-20 01:09:33

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.

我试图将我的数据从角形式发送到服务器控制器,在那里我使用这些数据来修改我的json文件,似乎他们使用ngResource来传递后端和FrontEnd数据,但我无法理解它是如何工作的以下是部分我判断的代码可能有助于解释我的问题。

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

注意:我在表单中使用了一个输入来解释问题,但它是多个字段的形式

2 个解决方案

#1


0  

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

在MEAN堆栈中,您在服务器端(节点)上使用Express来设置HTTP服务器,并且您的Angular前端应用程序通过HTTP协议与服务器通信。它没有包含在您发布的代码中,但我假设您的服务器端代码中设置了http服务器。就像是

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.

在本地计算机上,您将能够在localhost:8080*问这样设置的http服务器。

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.

这一行定义了一个路由处理程序,在这个上下文中它意味着“当你点击localhost:8080 /使用HTTP GET REQUEST进行测试时执行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.

updatesJsonConfig是一个快速中间件函数,可以访问req和res对象。如果要响应HTTP请求,则需要在updatesJsonConfig函数末尾调用res.send(),并将其作为参数发送。

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请求并处理响应。最简单的方法是使用$ http服务,如:

$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.

ngResource发出相同的HTTP请求,你真的不需要它。

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

所以服务器上的res.send(),客户端的$ http.get。

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.

为了通过HTTP发送表单数据,您需要使用$ http.post而不是$ http.get发出POST请求。 GET请求没有正文。

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

在服务器端,您需要更改路由以处理POST请求

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.

您还需要在express中包含body-parser模块,并且您将拥有一个req.body。

#2


0  

Finally after @marton answer I came up with a solution which respects meanjs framework,the connection between front end controller(angular controller) and backend controller(express controller/node ) is made by the help of angular service. To clarify my answer, when a user clicks submit button on a machine.client.view.html, a create function will be called which is defined in a machine.client.controller.js (see new client.controller.js below) but to send the data we will have to create an object with the data from the view(object created here is confInput) and we will pass this object to the service function createConfig which will post our data to our server controller with the help of angular service which uses resource object which wraps http request post. finally the most important thing is to modify our server route so that it can support post request( app.route('/testing').post(machine.updatingJsonConfig);

最后在@marton回答之后我提出了一个尊重meanjs框架的解决方案,前端控制器(角度控制器)和后端控制器(快速控制器/节点)之间的连接是通过角度服务的帮助完成的。为了澄清我的答案,当用户单击machine.client.view.html上的提交按钮时,将调用一个create函数,该函数在machine.client.controller.js中定义(请参阅下面的新client.controller.js)但是要发送数据,我们将使用视图中的数据创建一个对象(此处创建的对象是confInput),我们将此对象传递给服务函数createConfig,它将在角度服务的帮助下将我们的数据发布到我们的服务器控制器它使用包装http请求帖子的资源对象。最后,最重要的是修改我们的服务器路由,以便它可以支持发布请求(app.route('/ testing')。post(machine.updatingJsonConfig);

after this we can acces our data in our server controller by req.body.

在此之后,我们可以通过req.body访问我们的服务器控制器中的数据。

machine.client.service.js

(function () {
  'use strict';

  angular
    .module('machine')
    .factory('machineService', machineService);

  machineService.$inject = ['$resource'];

  function liferayService($resource) {
      var resource;

    resource = $resource('/testing',null,{
           createConfig : {
             method:'POST'
           }
    });

    // Public API
    return resource;
  }
})();

machine.client.controller.js

(function() {
  'use strict';

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

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

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


    //machine controller logic
    $scope.create = function () {
      // Creation of the object which contains user configurations input
      var confInput = {};
       confInput.nomProjet = this.nomProjet;
      
      machineService.createConfig(confInput,function (resource, headers) {
       //this function is executed when the post is succesful
      },function (response) {
        //this function is executed when the post returns an error
        console.error(response);
      });

    };

    init();

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

#1


0  

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

在MEAN堆栈中,您在服务器端(节点)上使用Express来设置HTTP服务器,并且您的Angular前端应用程序通过HTTP协议与服务器通信。它没有包含在您发布的代码中,但我假设您的服务器端代码中设置了http服务器。就像是

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.

在本地计算机上,您将能够在localhost:8080*问这样设置的http服务器。

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.

这一行定义了一个路由处理程序,在这个上下文中它意味着“当你点击localhost:8080 /使用HTTP GET REQUEST进行测试时执行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.

updatesJsonConfig是一个快速中间件函数,可以访问req和res对象。如果要响应HTTP请求,则需要在updatesJsonConfig函数末尾调用res.send(),并将其作为参数发送。

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请求并处理响应。最简单的方法是使用$ http服务,如:

$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.

ngResource发出相同的HTTP请求,你真的不需要它。

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

所以服务器上的res.send(),客户端的$ http.get。

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.

为了通过HTTP发送表单数据,您需要使用$ http.post而不是$ http.get发出POST请求。 GET请求没有正文。

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

在服务器端,您需要更改路由以处理POST请求

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.

您还需要在express中包含body-parser模块,并且您将拥有一个req.body。

#2


0  

Finally after @marton answer I came up with a solution which respects meanjs framework,the connection between front end controller(angular controller) and backend controller(express controller/node ) is made by the help of angular service. To clarify my answer, when a user clicks submit button on a machine.client.view.html, a create function will be called which is defined in a machine.client.controller.js (see new client.controller.js below) but to send the data we will have to create an object with the data from the view(object created here is confInput) and we will pass this object to the service function createConfig which will post our data to our server controller with the help of angular service which uses resource object which wraps http request post. finally the most important thing is to modify our server route so that it can support post request( app.route('/testing').post(machine.updatingJsonConfig);

最后在@marton回答之后我提出了一个尊重meanjs框架的解决方案,前端控制器(角度控制器)和后端控制器(快速控制器/节点)之间的连接是通过角度服务的帮助完成的。为了澄清我的答案,当用户单击machine.client.view.html上的提交按钮时,将调用一个create函数,该函数在machine.client.controller.js中定义(请参阅下面的新client.controller.js)但是要发送数据,我们将使用视图中的数据创建一个对象(此处创建的对象是confInput),我们将此对象传递给服务函数createConfig,它将在角度服务的帮助下将我们的数据发布到我们的服务器控制器它使用包装http请求帖子的资源对象。最后,最重要的是修改我们的服务器路由,以便它可以支持发布请求(app.route('/ testing')。post(machine.updatingJsonConfig);

after this we can acces our data in our server controller by req.body.

在此之后,我们可以通过req.body访问我们的服务器控制器中的数据。

machine.client.service.js

(function () {
  'use strict';

  angular
    .module('machine')
    .factory('machineService', machineService);

  machineService.$inject = ['$resource'];

  function liferayService($resource) {
      var resource;

    resource = $resource('/testing',null,{
           createConfig : {
             method:'POST'
           }
    });

    // Public API
    return resource;
  }
})();

machine.client.controller.js

(function() {
  'use strict';

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

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

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


    //machine controller logic
    $scope.create = function () {
      // Creation of the object which contains user configurations input
      var confInput = {};
       confInput.nomProjet = this.nomProjet;
      
      machineService.createConfig(confInput,function (resource, headers) {
       //this function is executed when the post is succesful
      },function (response) {
        //this function is executed when the post returns an error
        console.error(response);
      });

    };

    init();

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