首页 文章

在 DART 语言中将类从服务器返回到客户端

提问于
浏览
0

我使用 postgresql pub 这个服务器代码可用这里

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

输出是“供应商”

我可以将类从供应商发送到客户端,还是有另一种方法将我的 sql 输出发送到客户端。

谢谢

2 回答

  • 1

    实际上,您需要发送给客户端的是供应商对象列表,它是根据数据库结果而不是供应商类构建的。

    此外,您无法直接将对象写入响应,您需要序列化它。例如,您可以使用dart:convert库中的JSON编解码器将对象序列化为 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

  • 0

    我能够使用以下代码得到我想要的东西,但仍然对 know/learn 如何将其作为 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);
    }
    

相关问题