繁体   English   中英

使用 angularjs 使用 jsonp,(不能 CORS)

[英]Consuming jsonp with angularjs, (can't CORS)

我必须从另一台服务器(我无法控制)加载一个 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..)}]}

PS我在这里真的很绿,从今天早上开始我就有角度了!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM