AngularJS $http 和 jQuery AJAX 仅在移动浏览器上不触发

AngularJS $http and jQuery AJAX not firing on Mobile Browsers only

我有一个非常简单的 angular 测试应用程序调用 $http.get('http://localhost:3001/pets') 并使用 ngRepeat as < DIV >s 将它们写入 index.html

URL returns 数组有 3 objects 像这样:

[
    {
      "id": 1,
      "name": "cat",
      "location": "bedroom"
    },
....
]

然后使用 .success() 分配给 $scope.pets(实际是下面的代码)。

这在所有桌面浏览器中都能完美运行。

但是,当我使用 Chrome 或 Firefox(以及诺基亚上的 IE)在 Android 上加载页面时,它什么也不做。 没有效果 - NodeJS/Express 似乎甚至没有收到请求。

我尝试将 $http.get 替换为 $.ajax (... $scope.$apply...) - 代码如下。

我尝试使用服务、$deffered 和 $q,如下所述:http://chariotsolutions.com/blog/post/angularjs-corner-using-promises-q-handle-asynchronous-calls/

当我将Chrome Mobile/Firefox直接指向API时(http://localhost:3001/pets) 数据加载到浏览器没有问题。 我尝试对这些值进行硬编码,如下所示:

$scope.pets = [{"id": 1000, "name": "GOAT", "location": "EVERYWHERE"}];

... 然后执行 ngClick 调用 $http.get 并覆盖值。

同样,在桌面上运行良好 - 在移动设备上没有任何作用。

我确定我已经添加了 CORS headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Headers: X-Requested-With,content-type
Access-Control-Allow-Credentials: true

为什么?为什么这在 phone 浏览器上不起作用? 我用谷歌搜索了 2 天....

$scope.getPets = function () {
      $http.get('http://localhost:3001/pets')
    .success(function(response){
        //$scope.httpPets = response;
        console.log('Hello, this is dog with your GET request.')
        console.log(response);
    })
    .error(function(err){
      console.log("ERROR", err)
    })
    .then(function(response){
      console.log('Here then', response.data);
      $scope.httpPets = response.data;
    })
};

或者这个:

$scope.getPets = function(){
 $.ajax('http://localhost:3001/pets').success(function(data) {
        $scope.$apply(function(){ $scope.pets = data;});
        console.log(data);
    });
};

提前感谢您的任何建议。

检查你的URL。它说 localhost,所以它不会工作,除非你的服务器驻留在移动设备中(localhost 意味着服务器存在于同一台机器上)。

您需要提供正确的 url。

这意味着,如果您使用的是移动浏览器,您可能会在地址栏中输入 url,例如

http://192.168.1.2/

所以 http 调用应该是:

$http.get('http://192.168.1.2:3001/pets')

您只需要对此 url 进行 http 调用。

其他方式(广泛用于网站)是使用相对 URL,此方法将调用您所在的域并适用于所有网站。 例如,

$http.get('/pets')

将等于

$http.get('http://192.168.1.2:3001/pets')

检查这些..