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?
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'));
}
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With