以下代码适用于Dartium,但在浏览器中转换为JavaScript时则无效:
import 'dart:html';
var getReq = "http://127.0.0.1:8080/programming-languages";
void main() {
HttpRequest.getString(getReq).then((results) {
query("#text").text = results;
}).catchError((e) {
print("Oops! Encountered $e");
});
}
返回的错误是:
ERROR: Instance of 'Interceptor'
我正在关注JSON Web Service教程,完整来源的git repo是dartlang_json_webservice。
我使用的是Dart SDK版本0.7.2.1_r27268。
答案 0 :(得分:1)
您的代码在Dartium和Chrome中都适用于我。
然而,当我关闭服务器时,我得到了完全相同的错误。 我用chrome检查了控制台:
XMLHttpRequest cannot load http://127.0.0.1:8080/programming-languages.
Origin http://127.0.0.1:3030 is not allowed by Access-Control-Allow-Origin.
testhttpreq.html:1 Oops! Encountered Instance of 'Interceptor'
如果您在dart中运行此程序,则此错误类似于您收到的错误
XMLHttpRequest cannot load http://127.0.0.1:8080/programming-languages.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://127.0.0.1:3030' is therefore not allowed access.
Oops! Encountered Instance of 'HttpRequestProgressEvent'
在JavaScript中生成的toString(接收者是HttpRequestProgressEvent):
$.toString$0 = function(receiver) {
return $.getInterceptor(receiver).toString$0(receiver);
};
答案 1 :(得分:0)
问题是服务器返回的CORS标头无效:
/**
* Add Cross-site headers to enable accessing this server from pages
* not served by this server
*
* See: http://www.html5rocks.com/en/tutorials/cors/
* and http://enable-cors.org/server.html
*/
void addCorsHeaders(HttpResponse res) {
res.headers.add("Access-Control-Allow-Origin", "*, ");
res.headers.add("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
res.headers.add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
}
更换:
res.headers.add("Access-Control-Allow-Origin", "*, ");
使用:
res.headers.add("Access-Control-Allow-Origin", "*");
的工作原理。有关更多信息,请参阅Origin is not allowed by Access-Control-Allow-Origin。