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.
私は何を間違っていますか?