如何将ng-model传递给控制器函数,该控制器函数会向nodeJS服务器调用GET请求

How to pass an ng-model to a controller function which calls a GET request to the nodeJS server?

本文关键字:控制器 函数 nodeJS 服务器 调用 请求 GET ng-model      更新时间:2023-09-26

我要做的是:

  1. 从文本输入传递一个字符串,并绑定一个ng-model
  2. 到控制器中
  3. 调用服务中的GET请求
  4. 由节点服务器返回

下面是我到目前为止尝试的,它给了我以下错误:

Uncaught object angular.js:78

Main.html (1):

<div class="input-group input-group-lg">
    <input ng-model="businessName" type="text" class="form-control" placeholder="Business Name">
</div>

google.js (2):

var findGPlace2 = function() {
  GoogleService.findPlace2($scope.businessName).then(function(data) {
    $scope.gPlace2 = data;
  });
}
findGPlace2();

google-service.js (3):

this.findPlace2 = function(biz){
    var deferred = $q.defer();
    var obj = {
      business: biz
    };
    $http(
      {
        method: 'GET', 
        url: 'http://localhost:12200/find-google-place-2', 
        data: biz
      }).success(function(data) {
        deferred.resolve(data);
      }).error(function(err) {
      deferred.reject(err);
    });
    return deferred.promise;
  };

server.js (4):

//find google place 2
app.get('/find-google-place-2', function(req, res) {
  request('https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + req.data.biz + '&key=AIzaSyBvakIQ68QV2', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    res.send(body);
  }
})
});

这是一个很难调试的问题,因为错误没有在我的代码中给我一行。任何帮助都将非常感激。

==================================================

==================================================

更新:我从依赖项中删除了ng-autocomplete,并且Uncaught object错误消失了,我的角代码现在正在渲染,但是这个错误出现了:

GET http://localhost:12200/find-google-place-2 500 (Internal Server Error) angular.js:8380
    (anonymous function) angular.js:8380
    sendReq angular.js:8180
    $http.serverRequest angular.js:7921

我确信它与我如何传递我的req数据(从文本输入的字符串)有关,这是函数:

this.findPlace2 = function(biz){
    var deferred = $q.defer();
    var obj = {
      business: biz
    };
    $http(
      {
        method: 'GET', 
        url: 'http://localhost:12200/find-google-place-2', 
        data: biz
      }).success(function(data) {
        deferred.resolve(data);
      }).error(function(err) {
      deferred.reject(err);
    });
    return deferred.promise;
  };

这是它在我的server.js文件中实际运行的地方:

app.get('/find-google-place-2', function(req, res) {
  request('https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + req.data.biz + '&key=AIzaSyBvakIQ68QV2', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    //console.log(body) 
    res.send(body);
  }
})
});

您给我的内容确实不够,但是这里有一些关于如何进行调试的建议:

    这个问题是在http请求之前还是之后发生的?在您的服务器上使用console.log来查找。
  1. 使用chrome开发工具或firebug并在代码中设置断点,看看你走了多远。

这几乎肯定是(我猜)将所需依赖传递给模块时的错误(最常见的是ngRoute,但其他任何必需的都将抛出未捕获对象错误):

var app = angular.module('app', ['ngRoute']);

如果这对你来说不是一个简单的修复,一个容易获得实际调试消息的方法是使用angular的非minified源代码,并在Chrome Canary构建中运行它。

http://www.google.com/intl/en/chrome/browser/canary.html