我正在使用普通的http请求使用node.js从mysql数据库中删除值。但现在,只有静态删除值,而不是动态删除。我想通过提供id来动态删除数据。
const server = http.createServer();
const reqUrl = url.parse(req.url, true);
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let sql = "Delete from students where id=12";
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});
现在,运行此代码后 localhost:3000/delete只有 id=12 才会被删除。但我想这样做localhost:3000/delete?id=12将输入值作为 id 给出。
我尝试将 sql 命令指定为 “从 id=? 的学生中删除” ,但它给出了错误。我该如何解决这个问题?
最佳答案
这应该很简单。
您只需从请求中接收参数并将其附加到字符串中即可。
这是您更新后的代码。
server.on('request', (req, res) => {
if (reqUrl.pathname === '/delete'){
req.on('end', () => {
let studid = req.query.id; //Get the student id
let sql = "Delete from students where id="+studid; //append it to query
connection.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
})
res.end();
}
});
关于javascript - 使用 Node.js 中的删除请求动态从数据库中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54688559/