此dart代码将json字符串发送到下一个服务器端代码并接收响应。飞镖码有效。但是dart2js编译的js代码无法加载带有错误的http响应。这是dart2js中的错误吗?或者我做错了什么?
客户端代码:
import 'dart:html';
import 'dart:convert';
void main() {
querySelector(".button").onClick
.listen( (e) {
String url = 'http://127.0.0.1:8480';
HttpRequest request = new HttpRequest();
Map data = {
"int value" : 1,
"string value": 'Dartlang.'
};
String jsonData = JSON.encode(data);
print("json data sent = " + jsonData);
request
..open("POST", url, async: true)
..onLoadStart.listen((e) => print("Started loading"))
..onError.listen( (e) =>( print("Error occurred.")))
..onTimeout.listen((e) => (print("Server is not responding.")))
..onLoad.listen( (e) => (print("Response text = ${request.responseText}")))
..send(jsonData);
});
}
服务器端代码:
import 'dart:io';
import 'dart:async';
import 'package:http_server/http_server.dart';
void main() {
print("Listening for HTTP Requests...");
final HOST = InternetAddress.ANY_IP_V6;
final PORT = 8480;
HttpServer.bind(HOST, PORT).then((server) {
server.transform(new HttpBodyHandler())
.listen((HttpRequestBody body) {
HttpRequest request = body.request;
print("Recieved request from: ${request.connectionInfo.remoteAddress.address}");
var response = request.response;
addCorsHeaders(response);
response.write("You sent: ${body.body}");
response.close();
});
});
}
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");
}
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>HttprequestTester</title>
<link rel="stylesheet" href="httprequesttester.css">
</head>
<body>
<button class='button'>Send HTTP Request</button>
<script type="application/dart" src="httprequesttester.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
答案 0 :(得分:1)
我尝试了您的代码,它适用于Dartium(版本31.0.1650.48(240209)),Chrome(版本31.0.1650.63)和Debian Linux x64上的Firefox(26.0)。
但我想知道为什么当你服务于IPv6并使用IPv4地址进行访问时它会起作用。但我不是这些问题的专家。
答案 1 :(得分:1)
我怀疑这是一个错误。你能否在https://code.google.com/p/dart/issues提交申请? 添加足够的代码,以便其他人可以重现问题。感谢。