Question

I wrote an HTTP server with Dart, and now I want to parse form submits. Specifically, I want to handle x-url-form-encoded form submit from HTML forms. How can I do this with the dart:io library?

Was it helpful?

Solution

Use the HttpBodyHandler class to read in the body of an HTTP request and turn it into something useful. In the case of a form submit, you can convert it to a 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'));
      }
    });
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top