我用 Dart 写了一个 HTTP 服务器,现在我想解析表单提交。具体来说,我想处理从 HTML 表单提交的 x-url-form-encoded 表单。我怎样才能用dart:io
图书馆做到这一点?
问问题
316 次
1 回答
9
使用 HttpBodyHandler 类读取 HTTP 请求的正文并将其转换为有用的东西。在表单提交的情况下,您可以将其转换为地图。
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'));
}
});
});
}
于 2013-06-06T03:14:14.183 回答