deloki
deloki

Reputation: 1771

How to read HttpRequest data sent from client, on server

How do i read HttpRequest data sent by POST method from client, on the server, in Dart?

I send a message from the client like this:

HttpRequest request = new HttpRequest();
var url = "http://127.0.0.1:8081";
request.open("POST", url, async: false);

String data = 'hello from client'; 
request.send(data);

On server i am catching the request like this:

HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {

//DATA SHOULD BE READ HERE 



});
});

But i cant figure out how to actually read the data... There is not data property in HttpRequest nor anything else...

EDIT This is how i get the answer now:

HttpServer.bind('127.0.0.1', 8081).then((server) {
server.listen((HttpRequest request) {
  //DATA SHOULD BE READ HERE 
  print("got it");
  print(request.method);
  if(request.method == "POST") {
    print("got it 2");
    List<int> dataBody = new List<int>();
    request.listen(dataBody.addAll, onDone: () {
      var postData = new String.fromCharCodes(dataBody);
      print(postData);
      });
    }
 });
});

But for some reason the request.method is not "POST" but "OPTIONS", and if i change to if(request.method == "OPTIONS") , then print(postData) will still return nothing...

Upvotes: 6

Views: 7372

Answers (3)

Domenico Monaco
Domenico Monaco

Reputation: 1236

I have found this useful example with client/side code

GitHub json send to server Example

// XXX: Dart Editor thinks this is OK, but I haven't run it.

import 'dart:html';

String encodeMap(Map data) {
  return data.keys.map((k) {
    return '${Uri.encodeComponent(k)}=${Uri.encodeComponent(data[k])}';
  }).join('&');
}

loadEnd(HttpRequest request) {
  if (request.status != 200) {
    print('Uh oh, there was an error of ${request.status}');
    return;
  } else {
    print('Data has been posted');
  }
}

main() {
  var dataUrl = '/registrations/create';
  var data = {'dart': 'fun', 'editor': 'productive'};
  var encodedData = encodeMap(data);

  var httpRequest = new HttpRequest();
  httpRequest.open('POST', dataUrl);
  httpRequest.setRequestHeader('Content-type', 
                               'application/x-www-form-urlencoded');
  httpRequest.onLoadEnd.listen((e) => loadEnd(httpRequest));
  httpRequest.send(encodedData);
}

Upvotes: 1

Matt B
Matt B

Reputation: 6312

Right now, the handling of POST data is a little difficult. But essentially the HttpRequest itself has to be 'listened' to. HttpRequest is a stream itself. In particular it's a Stream<List<int>>. So basically your data may be passed to your HttpRequest as multiple List<int>'s. So we need to reconstruct the data then convert it into a string (assuming you're expecting a string, not binary data, etc). Here's more or less what I do:

HttpServer.bind('127.0.0.1', 8081).then((server) {
  server.listen((HttpRequest request) {
  if(request.method == "POST") {
    List<int> dataBody = new List<int>();
    request.listen(dataBody.addAll, onDone: () {
      var postData = new String.fromCharCodes(dataBody);
      // Do something with the data now.
    });
  }
  request.response.close();
});

Note that the request.listen(dataBody.AddAll, ...) basically calls List.addAll() each time data is to the server (in cases of larger data or multi-part forms it may not come all at once). This ensures we buffer it all until the stream indicates it is 'done' In which case we can now do something with the data we received, like convert it to a string.

Upvotes: 1

Allen Wayne
Allen Wayne

Reputation: 121

You can use the StringDecoder to tranform from "List of Int" to "String" from the HttpRequest. Since no matter if you send json, plain text, or png, Dart always send data in form of "List of Int" to the server.Another means is to use the Streams (http://www.dartlang.org/articles/feet-wet-streams/) tested on Heroku Steam v0.6.2 Dart Editor 0.4.3_r20602 Dat SDK 0.4.3.5_r26062

For example,

the client:

 import 'dart:html';
 import 'dart:json' as Json;
 import 'dart:async';
 import 'dart:uri';
 final String data = 'Hello World!';
 void _sendPNG(String pngData) {
 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(request.responseText); // output the response from the server
 }
                  }
 );
 // POST the data to the server Async
 print('Sending Photos to the server...');
 var url = "/png";
 request.open("POST", url);
 request.setRequestHeader("Content-Type", "text/plain");
 request.send(data);
 }

the server:

 import 'dart:io';
 import 'dart:async';
 import 'dart:json' as Json;
 import "package:stream/stream.dart";
 import 'package:xml/xml.dart' as xml;
 import 'package:unittest/unittest.dart';
 import 'package:rikulo_commons/mirrors.dart';
 void receivePNG(HttpConnect connect){
 var request = connect.request;
 var response = connect.response;
 if(request.uri.path == '/png' && request.method == 'POST')
  {
   String png='';
   response.write('The server received png request!');
   //read incoming List<int> data from request and use StringDecoder to transform   incoming data to string
   var stream = request.transform(new StringDecoder());
   stream.listen((value){
   print(value);
   //Hello World!
  }
  else
  {
   response.write('error');
   response.statusCode = HttpStatus.NOT_FOUND;
   connect.close();
   }
  }

configure.dart

 var _mapping = {
  "/": home,
  "/png": receivePNG,
 };

Upvotes: 1

Related Questions