【问题标题】:How to use ngResource when server is on a different localhost?当服务器位于不同的本地主机上时如何使用 ngResource?
【发布时间】:2016-06-02 00:40:36
【问题描述】:

我正在使用 Ionic 和 MEAN 堆栈构建应用程序。我的 express 服务器在 localhost:3000 上运行,而我的 Ionic 公共代码在 localhost:8100 上运行。根据我的研究,Ionic 似乎可以在与服务器不同的 IP 地址上运行,并且应该只使用 ngResource 来发送 $http 请求。

所以我在 server.js 中有一个这样的 RESTful 端点

router.get('/', function(req, res){
  res.json({"name":"Abdul"});
});

在 Ionic 客户端代码上,我发送如下请求:

app.controller('mainCtrl', function($scope, $resource){
    $scope.test = $resource('localhost:3000/');
    $scope.test_button = function(){
        console.log($scope.test);
    }
});

但是当我点击test_button,而不是[{"name":"Abdul"}] 登录控制台时,我收到以下空消息:

function Resource(value) {
     shallowClearAndCopy(value || {}, this);
}

谁能帮我连接客户端和服务器?

【问题讨论】:

    标签: angularjs express ionic-framework mean-stack ngresource


    【解决方案1】:

    $resource 对象只会创建一个具有getsaveupdate 等的对象。所以要调用服务器的get 方法,您需要调用$resource 对象的get 方法。该方法将返回 $promise 对象将提供一个承诺。你可以在上面放置.thenpromise,在其中你将在成功函数中获取数据。

    还有一件事是,当您从服务器返回数据时,您返回的是数组格式的对象。因此,在这种情况下,您需要指定 get 方法将返回数组,其中包含 isArray: true 选项。

    $scope.test = $resource('http://localhost:3000/', {}, {get: { isArray: true}});
    $scope.test.get().$promise.then(function(data){ //success function
       $scope.test = data;
    },function(error){ //error function
       console.log(error);
    })
    

    为了使您的应用程序更好,您可以将您的 $resource 对象移动到 service/factory 以使该调用可重用。

    app.service('dataService', function($resource){
       var resourceUrl = $resource('http://localhost:3000/', {}, {get: { isArray: true} });
       this.getData = function(){
          return resourceUrl.get().$promise;
       };
    })
    

    控制器

    app.controller('mainCtrl', function($scope, dataService){
        $scope.test_button = function(){
           dataService.getData().then(function(data){ //success function
               $scope.test = data;
           },function(error){ //error function
               console.log(error);
           })
        }
    });
    

    【讨论】:

    • 您好 Pankaj,感谢您的回复!我在这里对这段代码感到困惑。我在哪里放 $resource?我收到一个错误Cannot read property 'get' of undefined
    • 谢谢Pankaj,但我仍然有Cannot read property 'get' of undefined 错误。我添加了 ngResource 模块。上面的$scope.test.get()... 代码不应该至少对$resource 有一些引用吗?
    • @KangzeHuang 您不需要从控制器中删除$scope.test = $resource(localhost:3000/) 代码。看看编辑..将解决问题
    • 我修正了我的一个错误。对 localhost:3000 的引用应该在引号中。我复制了您的代码,但得到了不同的响应……一个带有data: null 的对象。但是在进步! :) 我在正确的轨道上吗?
    • 还有一个错误XMLHttpRequest cannot load localhost:3000. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
    猜你喜欢
    • 1970-01-01
    • 2019-08-14
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2017-11-26
    • 1970-01-01
    • 1970-01-01
    • 2017-11-24
    相关资源
    最近更新 更多