gpt4 book ai didi

dart - Google Dart简单联系表单

转载 作者:行者123 更新时间:2023-12-03 03:29:39 26 4
gpt4 key购买 nike

我正在尝试在Dart中创建联系表。到目前为止,我可以理解服务器需要包含以下内容:

服务器

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数据发送到服务器端?

json是处理表单所必需的还是有更好的方法?

最佳答案

您可以将form直接提交到服务器。内容将在post请求的正文中以URL编码发送。在服务器上,您可以使用 query_string package available on pub解码数据。

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

dependencies:
query_string: ">=1.0.0 <2.0.0"

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

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;
}

关于dart - Google Dart简单联系表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13648615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com