Google Dart简单联系人表单 [英] Google Dart Simple Contact form

查看:134
本文介绍了Google Dart简单联系人表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Dart中建立联系表单。到目前为止,我可以理解服务器需要包括如下:

I'm trying to make a contact form in Dart. So far I can understand the server needs to include something like the following:

服务器

app.addRequestHandler(
  (req) => req.method == 'POST' && req.path == '/adduser',
    (req, res) {
      //process json data
    };
  }
);

和客户的表单:

<form method="post" action="/adduser">
  <fieldset>
    <legend>Add a user</legend>
    <p><label>First name</label>
    <input name="user[first_name]"/></p>

    <p><label>Email</label>
    <input name="user[email]"/></p>

    <p class="actions"><input type="submit" value="Save"/></p>
  </fieldset>
</form>

客户端需要做什么才能将json数据发送到服务器端?

What needs to be done on the client side to get the json data to the server side?

是否需要json来处理表单,还是有更好的方法?

Is json necessary to process the form or is there a better way?

推荐答案

您可以直接向服务器提交表单。内容将在 post 请求的正文中以 URL编码发送。在服务器上,您可以使用 query_string 包解码数据

You can submit your form to server directly. The content will be sent URL-encoded in the body of the post request. On server, you can decode datas with the query_string package available on pub.

query_string 添加到您的pubspec.yaml文件:

Add query_string to your pubspec.yaml file:

dependencies:
  query_string: ">=1.0.0 <2.0.0"

您的服务器代码可能如下所示:

Your server code can looks like :

import 'dart:io';
import 'package:query_string/query_string.dart';

main() {
  final server = new HttpServer();
  server.listen('127.0.0.1', 8081);
  server.addRequestHandler((req) => req.method.toUpperCase() == 'POST' 
      && req.path == '/adduser', (request, response) {
    readStreamAsString(request.inputStream).then((body) {
      final params = QueryString.parse("?${body}");
      print(params["user[first_name]"]);
      print(params["user[email]"]);
      response.statusCode = HttpStatus.CREATED;
      response.contentLength = 0;
      response.outputStream.close();
    });
  });
}

Future<String> readStreamAsString(InputStream stream) {
  final completer = new Completer();
  final sb = new StringBuffer();
  final sis = new StringInputStream(stream);
  sis
    ..onData = () { sb.add(sis.read()); }
    ..onClosed = () { completer.complete(sb.toString()); }
    ..onError = (e) { completer.completeException(e); };
  return completer.future;
}

这篇关于Google Dart简单联系人表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆