我使用postgresql pub提供此服务器代码here
class Vendor {
String name;
String email;
}
void gVendors(HttpRequest req){
HttpResponse res = req.response;
addCorsHeaders(res);
print('${req.method}: ${req.uri.path}');
req.listen((List<int> buffer) {
connect(db).then((conn) {
conn.query('select * from VNDRS')
.map((row) => new Vendor()
..name = row.vname
..email = row.email)
.toList()
.then((List<Vendor> vendors) {
for (var c in vendors) {
print(c is Vendor); // this is correct
print(c.name); // this is correct
print(c.email); // this is correct
}
})
.then((_){
res.write(Vendor); // ??
res.close();
});
});
}, onError: printError);
}
当我在客户端检查并打印
时print(request.responseText);
输出是&#34;供应商&#34;
我可以将类从供应商发送到客户端,还是有另一种方法将我的sql输出发送到客户端。
感谢
答案 0 :(得分:1)
实际上,您需要发送给客户端的是供应商对象列表,它是根据数据库结果而不是供应商类构建的。
另外,您无法直接将对象写入响应,需要对其进行序列化。例如,您可以使用JSON
库中的dart:convert
编解码器将对象序列化为JSON:
import 'dart:io';
import 'dart:conver';
class Vendor {
String name;
String email;
Vendor([this.name, this.email]);
Vendor.fromJson(Map json) {
name = json["name"];
email = json["email"];
}
Map toJson() => {"name": name, "email": email};
}
void gVendors(HttpRequest req){
HttpResponse res = req.response;
addCorsHeaders(res);
print('${req.method}: ${req.uri.path}');
req.listen((List<int> buffer) {
connect(db).then((conn) {
conn.query('select * from VNDRS')
.map((row) => new Vendor(row.vname, row.email));
.toList()
.then((List<Vendor> vendors) {
for (var c in vendors) {
print(c is Vendor); // this is correct
print(c.name); // this is correct
print(c.email); // this is correct
}
res.write(JSON.encode(vendors.map((v) => v.toJson()).toList()));
res.headers.set("content-type", "application/json");
res.close();
});
}, onError: printError);
}
在此示例中,Vendor类具有从JSON转换为JSON的方法。在客户端,您还可以使用这些方法来解析响应:
var vendors = JSON.decode(request.response).map((o) => new Vendor.fromJson(o));
如果您不想为每个可序列化的类编写这些方法,您可以查找为您执行此任务的库,例如redstone_mapper。
答案 1 :(得分:0)
我能够使用以下代码获得我想要的东西,但仍然有兴趣了解/学习如何将其作为Class
void gVendors(HttpRequest req){
HttpResponse res = req.response;
addCorsHeaders(res);
print('${req.method}: ${req.uri.path}');
Future future() => new Future.value(true);
var db = 'postgres://postgres:pswd@localhost:5432/postgres';
req.listen((List<int> buffer) {
//var _theData = JSON.decode(new String.fromCharCodes(buffer));
var vndrs = <Map>[];
connect(db).then((conn) {
conn.query('select * from VNDRS')
.toList().then((rows) {
future()
.then((_){
for (var row in rows)
vndrs.add({
'name':row.vndrnum,
'num':row.vname,
'email':row.email
});
})
.then((_)=>res.write(JSON.encode(vndrs)))
.then((_)=>res.close());
});
});
}, onError: printError);
}