简体   繁体   English

如何使用Rikulo流将数据从客户端发送到服务器

[英]How to send data from client to server using Rikulo stream

I'm trying to use Rikulo stream, and i have some trouble when i want to send data from client to server. 我正在尝试使用Rikulo流,当我想将数据从客户端发送到服务器时,我遇到了一些麻烦。 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. 我已经采用了MVC模式,所以我希望控制器接收数据,然后使用dao类检查用户名是否存在。

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. dao类已经定义,所以我只想知道如何访问数据。

I hope that someone can help me. 我希望有人可以帮助我。

Since you're using POST, the JSON data will be in the HTTP request's body. 由于您正在使用POST,因此JSON数据将位于HTTP请求的正文中。 You can retrieve it there. 你可以在那里找回它。 Rikulo Commons has a utility called readAsJson . Rikulo Commons有一个名为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. 请注意,读取请求的主体是异步的,因此您必须返回Future实例以指示何时完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM