16

刚开始修补 Dart,我决定编写一个简单的 Http Server 和一个客户端。我的服务器代码:

#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.

我做错了什么?

4

3 回答 3

8

面临同样的问题。下面是我的服务器代码。它只是打印查询参数。添加了访问控制标头以解决此问题。

    HttpServer.bind('127.0.0.1', 8080).then((server){
    server.listen((HttpRequest request){     
      request.uri.queryParameters.forEach((param,val){
        print(param + '-' + val);
      });

      request.response.headers.add("Access-Control-Allow-Origin", "*");
      request.response.headers.add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");

      request.response.statusCode = HttpStatus.OK;
      request.response.write("Success!");
      request.response.close();
    });
  });

希望这可以帮助。

于 2013-06-18T09:51:29.200 回答
3

您可以简化您的生活并从同一主机:端口地址运行两个服务器/客户端脚本。在http://www.dartlang.org/articles/io/#web-servers有一个小型网络服务器示例,它也提供静态文件。添加您的“/api”处理程序并确保您的客户端文件位于同一目录中。示例服务器比运行在端口 3030 上的 Dart Editor 内置服务器慢很多。

于 2012-05-09T06:25:11.883 回答
1

这是我的解决方案:

request.response.headers.add("Access-Control-Allow-Origin", "*");
request.response.headers.add("Access-Control-Allow-Headers", "*");
request.response.headers.add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS");
于 2021-03-29T14:08:55.423 回答