首页 > 解决方案 > Flutter 对数据库提出请求

问题描述

我正在开发一个 Flutter 应用程序。我们有一个 PSQL 数据库,后台是 Node 服务器。在 Flutter 应用程序上,我显示了一些从数据库中成功获取的几何图形。现在,在对几何图形(例如线条)进行修改之后,我希望能够通过 put 请求更新数据库。

服务器如下:

app.put('/api/shape/:id', async (req,res) =>{

    let answer;

    if( req.body.shape_type == "line"){
        answer = await db.db.modify_line(req.params.id, req.body.info_shape);
    }

    res.send(answer);
});

db.js 文件如下所示:

modify_line : async function(id_shape, info_shape){
    console.log(info_shape);
    const result = await send_query("UPDATE line SET line = $2 WHERE id_shape = $1", [id_shape, info_shape]);
    return(result);

},

在 Flutter 应用程序上,我这样做:

_makeUpdateRequest() async {
var url = globals.URL + 'api/shape/' + globals.selectedShapeID.toString();

Map data;
if (globals.selectedType == globals.Type.line) {
  String lseg = "(" + globals.pLines[globals.selectedLineIndex].p1.dx.toString() + "," +
    globals.pLines[globals.selectedLineIndex].p1.dy.toString() + "," +
    globals.pLines[globals.selectedLineIndex].p2.dx.toString() + "," +
    globals.pLines[globals.selectedLineIndex].p2.dy.toString() + ")";
  data = {
    'shape_type': 'line',
    'info_shape': {
      'id_shape': globals.selectedShapeID.toString(),
      'line': lseg,
    }
  };

} 
http.Response response;
try {
  //encode Map to JSON
  print("encode Map to JSON");
  var body = json.encode(data);
  print(body);
  response = 
  await http.put(url,
    headers: {
      "Content-Type": "application/json"
    },
    body: body
  ).catchError((error) => print(error.toString()));

} catch (e) {
  print(e);
}
return response;
}

数据库“行”表的每一行都包含一个“shapeID”和“lseg”信息。

目前,当我尝试此代码时出现错误:

{ id_shape: '619',
  line:    '(19.5,100.6,20.5,50.9)' } 
fail____error: invalid input syntax for type lseg: "{"id_shape":"619","line":"(-19.5,100.6,20.5,50.9)"}"

我该如何塑造我的 lseg json?谢谢

标签: jsonflutterserverpsqlput

解决方案


好吧,在我看来,您正在将整个input_shape对象传递给 SQL 查询,看起来像这样,根据您的console.log

{
  id_shape: '619',
  line: '(19.5,100.6,20.5,50.9)'
}

显然,这对 PostgreSQL 无效。

我会说你的后端代码应该更像这样:

modify_line : async function(id_shape, info_shape){
    console.log(info_shape);
    const result = await send_query(
        "UPDATE line SET line = $2 WHERE id_shape = $1",
        // Reference "line" sub-object
        [id_shape, info_shape.line],
    );
    return(result);
},

您还应该注意线条的几何类型格式:

[ ( x1 , y1 ) , ( x2 , y2 ) ]

( ( x1 , y1 ) , ( x2 , y2 ) )

( x1 , y1 ) , ( x2 , y2 )

x1 , y1 , x2 , y2

通过阅读本文,我不能 100% 确定您的格式(带有前导和尾随括号)是正确的。


推荐阅读