POST
req.body
的内容是动态的(未选中的复选框不会被发送)。 SQL 更新和插入查询是硬编码的,尽管带有占位符。我要么必须填充 req.body
以匹配我的硬编码查询,要么从 req.body
: 动态创建查询
<script>
let sql = "UPDATE table SET ";
let data = {};
for (let [key, value] of Object.entries(req.body)) {
if (key != 'id' && key != 'submit') {
sql += "$" + key + "=? ,";
}
}
sql += " WHERE $id=" + req.body.id;
for (let [key, value] of Object.entries(req.body)) {
if (key != 'id' && key != 'submit') {
let newKey = "$" + key;
data.newKey = value;
}
}
</script>
什么是最好的,重建我的数据以匹配查询或构建查询以匹配我的数据?
您可以安装查询生成器。
npm install express knex sqlite3
const express = require('express');
const knex = require('knex');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
const db = knex({
client: 'sqlite3',
connection: {
filename: './data.sqlite3'
},
useNullAsDefault: true
});
app.put('/update', (req, res) => {
const data = req.body;
const id = data.id;
delete data.id;
delete data.submit;
db('table')
.where('id', id)
.update(data)
.then(() => {
res.status(200).json({ message: 'Successful!' });
})
.catch(error => {
res.status(500).json({ message: 'Failed', error });
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on ${PORT}`);
});