刚刚开始修改DART,我决定编写一个简单的http服务器和一个客户端.我的服务器代码:

#import("dart:io");

final HOST = "127.0.0.1";
final PORT = 8080;
final LOG_REQUESTS = true;

void main() {
  HttpServer server = new HttpServer();
  server.addRequestHandler((HttpRequest request) => true, requestReceivedHandler);
  server.listen(HOST, PORT);
  print("Server is running on ${PORT}."); 
}

void requestReceivedHandler(HttpRequest request, HttpResponse response) {
  var pathname = request.uri;
  var apiresponse="";
  if (LOG_REQUESTS) {
    print("Request: ${request.method} ${pathname}");
  }
  if(pathname == '/api'){
    response.headers.set(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers.add("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
    response.headers.add("Access-Control-Allow-Origin", "*");
    response.headers.add('Access-Control-Allow-Headers', '*');
    print('welcome to the good life');
    response.outputStream.writeString("API Call");
    response.outputStream.close();
  }
}

我的客户代码:

#import('dart:html');
#import('dart:json');

class dartjson {

  dartjson() {
  }

  void run() {
    write("Hello World!");
  }




  void fetchFeed(){
    XMLHttpRequest xhr = new XMLHttpRequest();
    var url = "http://127.0.0.1:8080/api";
    xhr.open("GET", url, true);
    xhr.setRequestHeader('Content-Type', 'text/plain');
    //xhr.setRequestHeader('Access-Control-Request-Headers', 'http://127.0.0.1:3030');
    xhr.send();
    print(xhr.responseText);
    document.query('#status').innerHTML = xhr.responseText;

  }



void main() {
  new dartjson().fetchFeed();
}

我不断发现错误:

XMLHttpRequest cannot load http://127.0.0.1:8080/api. Origin
http://127.0.0.1:3030 is not allowed by Access-Control-Allow-Origin.

我做错了什么?

推荐答案

您可以简化您的工作,并从相同的主机端口地址运行服务器/客户端脚本.在http://www.dartlang.org/articles/io/#web-servers点有一个小的网络服务器示例,它也提供静电文件.添加您的"/api"处理程序,并确保您的客户端文件位于同一目录中.示例服务器比端口3030上运行的DART编辑器内置服务器慢得多.

Dart相关问答推荐

将所有内容放在有序组中,但将括号中的字符组合在一起

Dart 中的const关键字放置有什么不同?

Dart 中的静态构造函数

如何在 Dart 中将代码迁移到 null 安全

是否从 Dart 中删除了interface关键字?

Flutter android 生成apk

那么在 Flutter 中缓存最简单的方法是什么?

如何通过 foreach 函数避免在 dart Map 中使用 await 键

表单的 TextFormField 中的多个光标(cursor)

如何在 Dart 语言中将 Future 转换为 List

Flutter类继承

Flutter 错误:The _ScaffoldLayout custom multichild layout delegate forgot to lay out the following child

Dart 2:Future 和 Future 之间的区别

如何在 Dart 中创建我们自己的metadata元数据?

如何从列表中的元素创建逗号分隔的字符串

Dart - 如何在每次测试之后或之前运行函数?

是否有任何官方计划在 Google App Engine 上支持 Dart?

在 Dart 中升序和降序排序?

如何在 Dart 中扁平化map列表?

Dart lambda/shortland 函数混淆