我已经用postgres数据库创建了一个nodejs api,用于处理所有的crud操作。我有一个.html页面,该页面由具有各种输入字段的表单组成,通过这些表单,我能够成功获取数据并将其成功发布到数据库。我想对表单应用“ put”请求,并使用该特定列(html表单输入字段之一)的新值更新该行,同时保留该行其他列的值。例如:如果我的表单中包含“姓名,电子邮件,密码,性别,资格,地址”之类的字段,并且如果我仅更新“电子邮件”字段,则我希望所有其他列值反映其值以及更新的字段
我在互联网上搜索了我的查询,但发现了与“更新所有行”或“更新多行的所有列”相关的帖子
//UPDATE A PROFILE
app.put('/home/profile/:name',(req,res,next)=>{
const name = req.params.name;
pg.connect(connectionString, (err, client, done) => {
if(err) {
done();
console.log(err);
return res.status(500).json({success:false, data:err});
}
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const gender = req.body.gender;
const qualification = req.body.qualification;
const address = req.body.address;
const query =client.query('UPDATE profile SET name = $1, email =$2, password =$3, gender=$4, qualification=$5, address=$6 WHERE name = $1',[name, email, password, gender, qualification, address],(err,rows,fields)=>{
if(!err)
res.send('Profile updated succesfully !!');
else
console.log(err);
})
})
})
//UPDATE A PROFILE
app.put('/home/profile/:name',(req,res,next)=>{
const name = req.params.name;
pg.connect(connectionString, (err, client, done) => {
if(err) {
done();
console.log(err);
return res.status(500).json({success:false, data:err});
}
const name = req.body.name;
const email = req.body.email;
const password = req.body.password;
const gender = req.body.gender;
const qualification = req.body.qualification;
const address = req.body.address;
const query =client.query('UPDATE profile SET name = ($1), email =($2), password =($3), gender=($4), qualification=($5), address=($6) WHERE name = ($1)',[name, email, password, gender, qualification, address],(err,rows,fields)=>{
if(!err)
{
query.on('row', (row) => {
results.push(row);
});
query.on('end', () => {
done();
console.log("Profile updated successfullyy !!")
// return res.json(results);
});
}else
console.log(err);
});
})
})
如果我在上面运行我的代码,则会收到类似-'Unexpected token,在JSON位置193'的错误
答案 0 :(得分:0)
与其在回叫中使用“字段”,不如使其简单地进行更新。并仅为修改后的字段构建此动态查询逻辑,并在其余调用PUT方法中传递这些键值以进行更新。 根据此参考动态构建列:Easier way to update data with node-postgres?接受了答案。
const query =client.query('UPDATE profile SET name = ($1), email =($2), password =($3), gender=($4), qualification=($5), address=($6) WHERE name = ($1)',[name, email, password, gender, qualification, address],
(error, results) => {
if (error) {
throw error
}
console.log('profile updated')
}
);
Ref:https://blog.logrocket.com/setting-up-a-restful-api-with-node-js-and-postgresql-d96d6fc892d8