Node.js:将插入的行从PostgreSQL v.11返回到浏览器 我不熟悉Node.js和PostgreSQL。
我正在使用insert查询创建post请求Node.js:将插入的行从PostgreSQL v.11返回到浏览器 我不熟悉Node.js和PostgreSQL。,node.js,postgresql,post,Node.js,Postgresql,Post,我正在使用insert查询创建post请求 如何将插入的值同时返回到浏览器 app.post('/car_create', (req, res) => { const make = req.body.create_make; const model = req.body.create_model; client.query(`INSERT INTO cars (make, model) VALUES ($1, $2)`, [make, model], (e
如何将插入的值同时返回到浏览器
app.post('/car_create', (req, res) => {
const make = req.body.create_make;
const model = req.body.create_model;
client.query(`INSERT INTO cars (make, model) VALUES ($1, $2)`, [make, model], (error, results) => {
if (error) {
throw error
}
res.status(201).send(`Car added with ID: ${results};`);
console.log(res);
res.end();
});
});
如何从响应中检索数据?
我是否需要以某种方式修改这一行
res.status(201).send(`Car added with ID: ${results};`);
首先,在PostgreSQL中插入值后,需要返回这些值。为此,在查询中添加一个
RETURNING
子句,如:INSERT INTO cars(make,model)value($1,$2)RETURNING id,make,model
。如果您有并且想要更多列,请在RETURNING
子句中添加更多列
然后,在回调中,results
变量应该包含有关查询的信息,包括它返回的内容(在行
键中)。您可以通过多种方式将其发送到客户端,但要以与当前类似的方式返回,您可以执行以下操作:
const {id, make, model} = result.rows[0]; // rows is an array of rows returned, and since we do a single INSERT we only have one row, with the returned columns from the query
res.status(201).send(`Car added with ID ${id}, make "${make}" and model "${model}".`);
如果您想在前端使用此数据,则可以将数据以JSON的形式发送,例如:
res.status(201).send(results.rows[0])代码>当我添加返回id、make、model时,我有一个错误。错误是什么?我假设你有一个名为id
的专栏,但是你可以不使用它试试吗?谢谢你的回答!