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

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

我正在尝试将我的数据从 angular 表单发送到服务器控制器 我使用这些数据修改我的 json 文件,在 meanjs 中他们似乎使用 ngResource 沟通后端和前端数据,但我不明白它是如何工作的 以下是我认为可能有助于解释我的问题的部分代码。

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);
};

注意:我在表单中使用一个输入只是为了说明问题,但它是一个包含多个字段的表单

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

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

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

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

这一行定义了一个路由处理程序,在这种情况下它意味着“当你点击 localhost:8080/testing with a HTTP GET REQUEST execute machine.updatingJsonConfig.

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

然后在客户端,您需要向服务器发出 http 请求并处理响应。最简单的方法是使用 $http 服务,例如:

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

ngResource 发出相同的 HTTP 请求,您在这里并不需要它。

因此在服务器上 res.send(),在客户端上 $http.get。

编辑:

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

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

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

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

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

之后我们可以通过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() {
    }
  }
})();