如何使用Dart解析表单提交?

Set*_*add 6 dart dart-io

我用Dart编写了一个HTTP服务器,现在我想解析表单提交.具体来说,我想从HTML表单处理x-url-form-encoded表单提交.我怎么能用dart:io图书馆这样做?

Set*_*add 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'));
      }
    });
  });
}
Run Code Online (Sandbox Code Playgroud)