Handling POST data on a Dart server

1,628 views
Skip to first unread message

Timothy Armstrong

unread,
Feb 6, 2013, 7:59:30 PM2/6/13
to mi...@dartlang.org
Hi all,

I've been writing some server-side Dart code, and I'm finding it overly complex to handle POST data.

In other languages, I can directly access the fields in the POST request. I want to be able to do something similar in Dart.

As far as I can tell, in order to read the POST data, I need to write a lot of boilerplate code. Currently, I have a request whose body looks like this:

------WebKitFormBoundaryu1Bfs2sYb2qBkWZR Content-Disposition: form-data; name="data" {"info":"Information here"} ------WebKitFormBoundaryu1Bfs2sYb2qBkWZR--

(this is what it looks like when you submit something using a FormData object; a more normal POST request still has the same problems as below, but the request body looks more like a simple query string)

In PHP, for example, I could get a JSON object from the request very simply:

$data = json_decode($_POST['data']);

In Dart, however, my (hacky) code looks like this:

var data; var buffer = new List<String>(); request.inputStream.onData = () { buffer.add(new String.fromCharCodes(request.inputStream.read())); }; input.onClosed = () { var fullString = buffer.join('');
var startIndex = fullString.indexOf('{');
var endIndex = fullString.lastIndexof('}') + 1; data = JSON.parse(fullString.slice(startIndex, endIndex)); };

I understand that streams are more powerful, but for most use cases, most people don't need them and I don't think that the average developer shouldn't have to write a stream parser just to handle a bit of form data. I'd like there to be built-in support for perhaps a Future-based access to an already parsed version of the POST data, maybe something like this:

request.getPostData().then((post) {
var data = post['data'];
});

While still not as simple as in some other languages, I think this would make the common use cases a lot more pleasant.

Thoughts?

--
Timothy

Bob Nystrom

unread,
Feb 6, 2013, 8:11:18 PM2/6/13
to General Dart Discussion

On Wed, Feb 6, 2013 at 4:59 PM, Timothy Armstrong <timarm...@google.com> wrote:
Thoughts?

Take a look at the http package on pub. This is what pub itself uses for doing HTTP requests. It's got a bunch of docs with examples and stuff you can see here.

I'm not sure if it does exactly what you want, but it might get you closer. I think it would look something like:

import 'dart:json' as json;
import 'package:http/http.dart' as http;

main() {
  http.post(url, fields: { ... }).then((response) {
    var data = json.parse(response.body)['data'];
  });
}

Cheers!

- bob

Timothy Armstrong

unread,
Feb 6, 2013, 8:19:39 PM2/6/13
to mi...@dartlang.org
That library seems to be client-side, and your example handles 'response.body'. My question is about server-side Dart, where I've submitted some data as POST data from the client and trying to handle receiving that on the server. It's the handling on the server side that's the problem.

Thanks anyway!

--
Timothy


--
Consider asking HOWTO questions at Stack Overflow: http://stackoverflow.com/tags/dart
 
 

Don Olmstead

unread,
Feb 6, 2013, 9:17:40 PM2/6/13
to mi...@dartlang.org
I haven't seen anyone handling multi-part forms on the server yet. I know this project is working towards it https://github.com/Daegalus/fukiya.

Also Dart doesn't seem to have a base64 decode in the standard libraries, despite it living in SVN http://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/runtime/bin/base64.dart?spec=svn6998&r=6998

Allan MacDonald

unread,
Feb 7, 2013, 12:44:15 AM2/7/13
to mi...@dartlang.org
Timothy,

I was working on a library a long time ago (almost a year ago) when Dart was early on, and I did get it working at one point for uploading files using multi-part. It requires a great deal of polish and refactoring.

It has been a while since I looked at it, but it would not take much for me to upgrade it to the more recent releases of Dart, and make it available if you would like to contribute to it or find anything useful. I will not be spending much time on it for a few months as I am knee deep in a few other more important Dart projects around web_ui.

Let me know if you are interested.

Allan

Mads Ager

unread,
Feb 7, 2013, 2:08:43 AM2/7/13
to General Dart Discussion
We definitely need to make handling of POST easier on the server side.

We are currently rewriting dart:io to use the lib v2 streaming APIs which means that new feature work is on hold for a little while.

Here is the bug to star: http://dartbug.com/2488. :-)

Cheers,    -- Mads

Timothy Armstrong

unread,
Feb 7, 2013, 1:37:51 PM2/7/13
to mi...@dartlang.org
Allan - I wouldn't mind taking a look if you have a Github repo or something. You don't need to do any polish or refactoring, I'd just like to take a quick peek to see how you approached things.

Mads - Thanks, starred.

Seth Ladd

unread,
Feb 7, 2013, 6:11:20 PM2/7/13
to General Dart Discussion
Timothy,

You might try some of the more full-featured web server frameworks for Dart. I've not tried them, but check out:


Would love to know if any of these help! :)

Asmaa Aljuhani

unread,
Jul 28, 2013, 7:00:57 PM7/28/13
to mi...@dartlang.org
Hi Timothy,
I am new to Dart and I think I am facing the same issue here.

I am trying to send data from Dart app to google-app-engine server. I have been trying many things but nothing worked till now.

Here is the Dart code:

void sendData(String data) {
HttpRequest request = new HttpRequest(); // create a new XHR

// add an event handler that is called when the request finishes
request.onReadyStateChange.listen((_) {
  if (request.readyState == HttpRequest.DONE &&
      (request.status == 200 || request.status == 0)) {
    // data saved OK.
    print("succesfully posted data");
    print(request.responseText); // output the response from the server
  }
});

// POST the data to the server
var url = "http://xyz.appspot.com/";
request.open("POST", url, async: false);
request.send(data); // perform the async POST
}

This code works and I have no problem in it. This is my server side function which is in python:

 def post(self):

    #session= self.request.get('Session' , DEFAULT_SESSION_KEY)

    session= DEFAULT_SESSION_KEY

    Components = Circuit_Components(parent=session_key(session))
    Components.components = self.request.get(self.request.arguments()[0])
    Components.put()

    query_params = {'Session': session}
    self.redirect('/?' + urllib.urlencode(query_params))

Would anyone help me in this.

Thanks

Asmaa

Seth Ladd

unread,
Jul 31, 2013, 1:53:14 PM7/31/13
to General Dart Discussion
Hi Asmaa,

This is a great question for Stack Overflow. For HOWTO questions, there is an active and helpful community there. Can I ask you to post this to Stack Overflow? It also makes it easy for others to find the answer.

FWIW I can recommend HttpRequest's convenient request static method. http://api.dartlang.org/docs/releases/latest/dart_html/HttpRequest.html#request

Here's an example:

HttpRequest.request('/cats',
    method: 'POST',
    sendData: json.stringify({'name':name}),
    requestHeaders: {'Content-Type': 'application/json'})
  .then((req) {
    // do something with the completed request
  })
  .catchError((e) => print(e));


Thanks!
Seth


--
For other discussions, see https://groups.google.com/a/dartlang.org/
 
For HOWTO questions, visit http://stackoverflow.com/tags/dart
 
To file a bug report or feature request, go to http://www.dartbug.com/new
 
 

Reply all
Reply to author
Forward
0 new messages