How to send data from client to server using Rikulo stream

437 Views Asked by At

I'm trying to use Rikulo stream, and i have some trouble when i want to send data from client to server. Suppose that i have a registration form and i want send a request to check if that username already exist in my database. I have adopted MVC pattern, so i want that the controller received data and then, using a dao class, check if username exist or not.

In client side i have this lines of code

InputElement username = query('#username');
document.query("#submit").onClick.listen((e) {
  HttpRequest request = new HttpRequest();

  var url = "/check-existing-username";
  request.open("POST", url, async:true);
  request.setRequestHeader("Content-Type", "application/json");
  request.send(stringify({"user": username.value}));

});

Is this the correct way to send data?

Here my server side code

void main(){

  Controller controller = new Controller();

  var _mapping = {
              "/": controller.home,
              "/home": controller.home,
              "/check-existing-username" : controller.checkUsername
  };

  new StreamServer(uriMapping: _mapping).start();

And my controller method

void checkUsername(HttpConnect connect) {
  //How to access data received from client?
}

The dao class is already defined, so i want only know how to access data.

I hope that someone can help me.

1

There are 1 best solutions below

0
On BEST ANSWER

Since you're using POST, the JSON data will be in the HTTP request's body. You can retrieve it there. Rikulo Commons has a utility called readAsJson. You can utilize it as follows.

import "package:rikulo_commons/convert.dart";

Future checkUsername(HttpConnect connect) {
  return readAsJson(connect.request).then((Map<String, String> data) {
      String username = data["user"];
      //...doa...
  });
}

Notice that reading request's body is asynchronous, so you have to return a Future instance to indicate when it is done.