json - 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?谢谢
解决方案
好吧,在我看来,您正在将整个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% 确定您的格式(带有前导和尾随括号)是正确的。
推荐阅读
- algorithm - 为什么二进制搜索算法适用于这个一维“寻峰”问题?
- arrays - 循环数组:While 循环和 2D 数组
- swift - 对于面临屏幕问题的新 IOS 更新 ios 13.5.1
- python - python中的递归未分配lambda
- android - 如何使用 `cv2.putText` (Android +OpenCV) 在图像上绘制度数符号 (º) 特殊字符?
- datetime - 在 Flutter 中,我得到了一个 DateTime [yyyy-MM-dd 00:00:00.000] 我如何才能将其仅转换为 [yyyy-MM-dd]?
- python - 在“uv”模式下绘制时获取箭袋箭头(尖端和底部)的坐标
- google-apps-script - 有没有办法将 Gmail 附件保存为 MP4?
- flutter - 带有 onPressed 索引的不同页面上的轮播图像
- c - C 编译器使用 Cray 上 Fortran 模块中定义的变量