简体   繁体   English

dart:HTTPRequest在JS中不起作用,但仅在Dartium中起作用

[英]dart: HTTPRequest does not work in JS but in Dartium only

The following code works in Dartium, but not when converted to JavaScript in a browser: 以下代码在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");
  });
}

The error returned is: 返回的错误是:

ERROR: Instance of 'Interceptor'

I'm following the JSON Web Service tutorial, the git repo for the complete source is dartlang_json_webservice . 我正在关注JSON Web服务教程,完整源的git repo是dartlang_json_webservice

I'm using Dart SDK version 0.7.2.1_r27268. 我正在使用Dart SDK版本0.7.2.1_r27268。

Your code works for me both in Dartium and Chrome. 您的代码在Dartium和Chrome中都对我有效。

However, I get precisely the same error when I turn off the server. 但是,当我关闭服务器时,会得到完全相同的错误。 I checked the console in 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' 

This is error similar to what you receive if you run this program in dart 这与在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'

with the generated toString in JavaScript (receiver being HttpRequestProgressEvent): 使用JavaScript中生成的toString(接收者为HttpRequestProgressEvent):

$.toString$0 = function(receiver) {
 return $.getInterceptor(receiver).toString$0(receiver);
};

The problem is the server is returning a CORS header which is not working: 问题是服务器返回的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");
}

Replacing: 更换:

res.headers.add("Access-Control-Allow-Origin", "*, ");

with: 与:

res.headers.add("Access-Control-Allow-Origin", "*");

works. 作品。 See Origin is not allowed by Access-Control-Allow-Origin for futher information. 有关更多信息,请参见Access-Control-Allow-Origin不允许使用Origin

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

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