我正在玩dart http服务器,我不知道如何阅读http请求中发送的实际内容:“{'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();
});
});
}
答案 0 :(得分:8)
您可以使用:
import 'dart:convert' show UTF8;
Future<String> content = UTF8.decodeStream(request);
答案 1 :(得分:6)
对于想要查看完整代码的人,Alexandre Ardhuin给出了简短而正确的答案:
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();
}