【问题标题】:Consuming jsonp with angularjs, (can't CORS)用 angularjs 消费 jsonp,(不能 CORS)
【发布时间】:2017-06-03 07:06:27
【问题描述】:

我必须从另一台服务器(我无法控制)加载 JSON 文件。经过几个小时的研究发现,JSONP 是回答我的请求的肮脏黑客。

我正在使用 nodejs,使用 gulp 为 localhost:3000 上的站点提供服务。 从 localhost:8000 加载 JSON

我能够从一个我不需要的 URL(在 Internet 上随机找到)使用我没有使用我的 URL 的相同代码获得一个工作示例。

这让我想知道我是否正在尝试读取文件,就像它不是一样?据我研究,不需要将 JSON 解析为 JSONP。我在正确的轨道上吗?

下面是我说的代码:

(function () {
'use strict';

angular
    .module('qwe.asd')
    .controller('UsersController', UsersController);

/** @ngInject */
function UsersController($http, $log, $sce) {

    var vm = this;
    var trustedUsersAPI = "http://localhost:8000/users?callback=JSON_CALLBACK";
    $sce.trustAsResourceUrl(trustedUsersAPI);

    $http.jsonp(trustedUsersAPI, {
            'callback': 'JSON_CALLBACK'
        })
        .success(function (data) {
            $log.log("request 1 - OK");
            $log.log(data);
            vm.users = data;
        })
        .error(function () {
            $log.log("request 1 - KO");
        });

    var url = "http://public-api.wordpress.com/rest/v1/sites/wtmpeachtest.wordpress.com/posts?callback=JSON_CALLBACK";
    $sce.trustAsResourceUrl(url);

    $http.jsonp(url)
        .success(function (data) {
            $log.log("request 2 - OK");
            $log.log(data);
        })
        .error(function () {
            $log.log("request 2 - KO");
        });


}
})();

并且生成的日志...

angular.js:13424 request 1 - KO
angular.js:13424 request 2 - OK
angular.js:13424 Object {found: 12, posts: Array[12]}

最后,我正在(误)阅读的 JSON 文件:

我需要但我不能拥有的那个

[{"id":0,"firstname":"front","lastname":"end","email":"frontend@example.com"},{"id":1,"firstname":"back","lastname":"end","email":"backend@example.com"},{"id":2,"firstname":"john","lastname":"doe","email":"johndoe@example.com"},{"id":3,"firstname":"dev","lastname":"eloper","email":"developer@example.com"},{"id":4,"firstname":"ad","lastname":"min","email":"admin@example.com"}]

我不需要但工作正常的那个

{"found":12,"posts":[{"ID":XX,"site_ID":XXXX,"author":XXXX(..POSTS DATA WITH NO VALUE HERE..)}]}

附:我在这里真的很绿,从今天早上开始我就变胖了!

【问题讨论】:

  • 那么...什么有效,什么无效?
  • “经过几个小时的研究发现,JSONP 是回答我请求的肮脏黑客。” 仅当该服务器支持 JSONP 时。对于 JSON 与 JSONP,服务器发回的内容不同。 JSON 示例:{"foo":"bar"} JSONP 示例:callback({"foo":"bar"})
  • trustedUsersAPI 中包含的 JSON 可通过网络选项卡(在 Chrome 的 devtools 上)访问,但不知何故无法通过代码访问。 @KevinB
  • @ManuelGarridoGutierrez 自动,由服务器,是的。 如果服务器支持 JSONP。
  • @ManuelGarridoGutierrez — 您的客户端库将自动生成它的客户端。当且仅当服务器支持 JSONP 时,服务器才会生成它的服务器端作为响应。

标签: javascript angularjs node.js http jsonp


【解决方案1】:

对于那些追随我的人,我走错了路。感谢评论者,我了解到服务器必须支持 JSONP(就像 CORS 一样)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2015-04-12
    • 2014-09-22
    • 1970-01-01
    • 2014-07-07
    • 2015-07-06
    • 2013-02-14
    相关资源
    最近更新 更多