I am playing with dart http server and I'm not sure how to read the actual content sent in the http request: "{'text':'some text data.'}"
import 'dart:io';
void main() {
HttpServer.bind('127.0.0.1', 3000).then((server){
server.listen((HttpRequest request) {
print("request made");
request.response.write('''
<html>
<head>
</head>
<body>
<pre>
HELLO:
request info:
method: ${request.method}
uri: ${request.uri}
content length: ${request.contentLength}
content : //HOW DO I GET THIS?
</pre>
<script>
var req = new XMLHttpRequest();
req.open("POST","/a_demonstration");
req.send("{'text':'some text data.'}");
</script>
</body>
</html>
''');
request.response.close();
});
});
}
You can use :
import 'dart:convert' show utf8;
Future<String> content = utf8.decodeStream(request);
Alexandre Ardhuin gave the short and correct answer, for anyone wanting to see full code:
import 'dart:io';
import 'dart:convert' show UTF8;
void main() {
HttpServer.bind('127.0.0.1', 3000).then((server){
server.listen((HttpRequest request) {
print("request made");
if(request.contentLength == -1){
_sendResponse(request, '');
}else{
UTF8.decodeStream(request).then((data)=>_sendResponse(request,data));
}
});
});
}
_sendResponse(HttpRequest request, String requestData){
request.response.write('''
<html>
<head>
</head>
<body>
<pre>
HELLO:
request info:
method: ${request.method}
uri: ${request.uri}
content length: ${request.contentLength}
content: ${requestData}
</pre>
<script>
var req = new XMLHttpRequest();
req.open("POST","/a_demonstration");
req.send("{'text':'some text data.'}");
</script>
</body>
</html>
''');
request.response.close();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With