AngularJS从其他域请求JSON

AngularJS request JSON from other domain

本文关键字:请求 JSON 其他 AngularJS      更新时间:2023-09-26

我正在尝试使用以下代码从Wikia API检索数据。但一切似乎都失败了。据我所知,CORS必须在服务器上启用,我正试图从中检索数据。但是我不知道Wikia是不是这样。所以JSONP似乎是唯一的方法。但是我得到错误

XMLHttpRequest cannot load http://adventuretime.wikia.com/api/v1/Articles/List?expand=1&category=Episodes&limit=200. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://website.com' is therefore not allowed access.

我已经阅读了AngularJS文档:https://docs.angularjs.org/api/ng/service/$http

w3schools: http://www.w3schools.com/angular/angular_http.asp

和许多关于stackoverflow的问题。我的代码有什么可怕的错误吗?Angular应该原生支持CORS和JSONP请求

我的代码如下:

index . html

<!DOCTYPE html>
<html ng-app="episodes">
<head>
    <meta charset="UTF-8">
    <title>Episodes</title>
    <script src="angular.js"></script>
    <script src="workshop.js"></script>
</head>
<body ng-controller="AppController as app">
    <table>
        <thead> 
            <tr>
                <th>Title</th>
                <th>Url</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="episode in app.episodes">
                <td>{{episode.title}}</td>
                <td>{{episode.url}}</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

workshop.js

(function(){
    angular
        .module('episodes', [])
        .controller('AppController', function($http){
            var app = this;
            app.episodes = $http({
                url: "http://adventuretime.wikia.com/api/v1/Articles/List?expand=1&category=Episodes&limit=200",
                dataType: "jsonp"
            });
        });
})();

任何帮助都是感激的!

提前感谢您的帮助

编辑

响应头是:

Content-Encoding: gzip
X-Content-Type-Options: nosniff
X-Cacheable: YES
Age: 0
X-Cache: ORIGIN, MISS, MISS
Content-Length: 21965
X-Served-By: ap-s21, cache-wk-sjc3160-WIKIA, cache-fra1233-FRA
X-Backend-Response-Time: 2.267
Server: Apache
X-Timer: S1439118796.704444,VS0,VE2447
Vary: Accept-Encoding
Content-Type: application/json; charset=utf-8
Cache-Control: public, max-age=86400
Accept-Ranges: bytes
X-Cache-Hits: ORIGIN, 0, 0

尝试使用$http.jsonp(url);进行跨域请求;

Angularjs api - $http.jsonp();

据我所知,CORS必须在服务器上启用

正确的。

但是我不知道Wikia是不是这样。

因为你得到了错误信息:

没有'Access-Control-Allow-Origin'头


所以JSONP似乎是唯一的方法。

JSONP是围绕同源策略工作的一种hack。它不像CORS(设计用于提供显式权限)那样优雅,但它要求服务器用JSONP表示数据。

错误信息:

拒绝执行来自'*&callback=JSON_CALLBACK'的脚本,因为它的MIME类型('application/json')不可执行,并且启用了严格的MIME类型检查。

表示对HTTP请求的响应不是JSONP(它将具有application/javascript Content-Type),因此服务器不支持它。


一个网站不能指示web浏览器向另一个服务器发出HTTP请求,并在没有得到请求所在站点的明确许可的情况下向其JavaScript提供响应。

您需要考虑一个替代方案,其中对服务器的请求不是来自浏览器。例如,通过您自己的服务器代理请求