【发布时间】:2015-11-01 04:37:08
【问题描述】:
我正在尝试使用以下代码从 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
【问题讨论】:
-
JSONP 也必须得到服务器的支持。 (返回的 JS sn-p 需要调用你的回调。)
-
@Noah 你能解释一下回调吗?服务器似乎支持 JSONP,但我现在收到 MIME 错误
-
关于该主题的维基百科文章解释:en.wikipedia.org/wiki/JSONP
标签: javascript ajax json angularjs cors