This dart code sends a json string to the next server-side code and receives a response back. The dart code works. But the dart2js-compiled js code fails to load the http response with an error. Is this a bug in dart2js? Or am I doing something wrong?
Client-side code:
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);
});
}
Server-side code:
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>
I suspect this is a bug. Can you please file it at https://code.google.com/p/dart/issues ? Add enough code so that others can reproduce the problem. Thanks.