Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a form submission with Dart?

Tags:

dart

dart-io

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?

like image 695
Seth Ladd Avatar asked Jun 06 '13 03:06

Seth Ladd


1 Answers

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'));
      }
    });
  });
}
like image 123
Seth Ladd Avatar answered Oct 16 '22 03:10

Seth Ladd