【问题标题】:angularjs $http.jsonp goes to .error instead of .success even when 200 is received即使收到 200,angularjs $http.jsonp 也会转到 .error 而不是 .success
【发布时间】:2013-08-04 16:54:08
【问题描述】:

我正在构建一个 AngularJS 应用程序,它调用从数据库获取数据的 NodeJS 服务器。 NodeJS 返回一个 JSON.stringify(someArrayWithData)。

这里是 AngularJS 代码:

$scope.getMainGroups = function(){
    $http.jsonp("http://127.0.0.1:3000/get/MainGroups?callback=JSON_CALLBACK").success(function(data, status, headers, config) {
            $scope.MainGroups = data;
        }).error(function(data, status, headers, config) {
            $scope.MainGroups = status;
        });
};

$scope.MainGroups 将转到 .error 而不是成功,即使我可以在 chrome 调试器中看到结果返回(200 ok)。

我错过了什么?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    您必须在服务器端返回有效的 JSON 响应。 200 OK 只是注入 DOM 的 GET 请求。我敢打赌,您没有从服务器返回具有正确响应代码的有效 JSON 响应。

    这是一个关于如何在服务器端 (PHP) 构建响应的示例: Simple jQuery, PHP and JSONP example?

    【讨论】:

    • 我使用 node.js 作为我的服务器端,我正在返回 res.send(JSON.stringify(mainGroupsArray));
    【解决方案2】:

    正如here 的回答,您需要更改 NodeJS 响应。 JSONP 答案需要以 AngularJS 在 URL 中添加的确切文本开头(例如 'angular.callbacks._1')。

    // changes in your server script used by NodeJS
    // Required for JSONP calls, 'callback' matches the '?callback=JSON_CALLBACK'
    app.set('jsonp callback name', 'callback'); 
    
    // ... in your response change json to jsonp
    res.jsonp(votes);
    

    进行这些更改后,当服务器在参数中检测到“回调”时,答案如下:

    /**/ typeof angular.callbacks._1 === 'function' && angular.callbacks._1([{"votes":3,"title":"new topic", etc...

    现在是的,AngularJS 正确地回调了“成功”函数。

    【讨论】:

      猜你喜欢
      • 2018-08-19
      • 2016-08-03
      • 2015-04-22
      • 2014-11-08
      • 1970-01-01
      • 2022-06-11
      • 2021-08-21
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多