我用Dart写了一个HTTP服务器,现在我要解析表单提交。具体来说,我想从HTML表单处理x-url-form-encoded表单提交。如何使用dart:io
库执行此操作?
答案 0 :(得分:9)
使用HttpBodyHandler类读取HTTP请求的正文并将其转换为有用的内容。如果是表单提交,您可以将其转换为Map。
import 'dart:io';
main() {
HttpServer.bind('0.0.0.0', 8888).then((HttpServer server) {
server.listen((HttpRequest req) {
if (req.uri.path == '/submit' && req.method == 'POST') {
print('received submit');
HttpBodyHandler.processRequest(req).then((HttpBody body) {
print(body.body.runtimeType); // Map
req.response.headers.add('Access-Control-Allow-Origin', '*');
req.response.headers.add('Content-Type', 'text/plain');
req.response.statusCode = 201;
req.response.write(body.body.toString());
req.response.close();
})
.catchError((e) => print('Error parsing body: $e'));
}
});
});
}