我正在尝试在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是否需要处理表单或有更好的方法吗?
答案 0 :(得分:2)
您可以直接将form
提交给服务器。内容将在post
请求的正文中发送网址编码。在服务器上,您可以使用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;
}