gpt4 book ai didi

reactjs - 如果未填写所有字段,如何向数据库添加记录?

转载 作者:行者123 更新时间:2023-12-03 22:39:09 28 4
gpt4 key购买 nike

在我的 React 应用程序中,我确实将行添加到数据库(PostgreSQL)中:

addToDatabase() {
fetch(`${'127.0.0.1:3000'}/add`, {
method: 'PUT',
body: JSON.stringify(this.state.person),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
...
}

this.state.person 通常有下一个格式:
{id: 1, surname: 'Jones', name: 'John', city: 4}

在后端,我使用 sequelize 向数据库添加行:
app.route('/add')
.put((req, res) => {
Person.create({
surname: req.body.surname,
name: req.body.name,
city: req.body.city
});
res.send(JSON.stringify({ success: true }));
});

有时我需要添加一行只有姓氏。这样, this.state.person 有下一个格式:
{id: 1, surname: 'Jones'}

但我收到一个错误:
Unhandled rejection SequelizeDatabaseError: invalid input syntax for integer: ""

后端总是等待所有字段填满。如何添加带有选择性填充字段的记录?

最佳答案

req.body.city 将设置为未定义,这将导致错误

Use NULL for "empty" values in a numeric column 
The empty string '' can only be used in character types like text or varchar

关于reactjs - 如果未填写所有字段,如何向数据库添加记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52931520/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com