AngularJS从其他域

时间:2015-08-08 23:46:41

标签: javascript ajax json angularjs cors

我正在尝试使用以下代码从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

2 个答案:

答案 0 :(得分:0)

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

Angularjs api - $http.jsonp();

答案 1 :(得分:0)

  

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

正确。

  

但是我不知道Wikia是否属于这种情况。

因为您收到错误消息:

  
    

否&#39;访问控制 - 允许 - 来源&#39;头

  

...它未启用。

  

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

JSONP是一个解决相同原始政策的黑客。它不像CORS那样优雅(它旨在提供明确的权限),但它要求服务器在JSONP中表达数据。

错误消息:

  
    

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

  

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

网站无法指示网络浏览器向其他服务器发出HTTP请求,并在未经请求的网站明确许可的情况下向其JavaScript提供响应。

您需要查看对服务器的请求不是来自浏览器的替代方案。例如通过您自己的服务器代理请求。

相关问题