首页 > 解决方案 > 使用node.js中的删除请求从数据库中动态删除数据

问题描述

我正在使用普通的 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=? 的学生中删除?” ,但它给出了错误。我该如何解决这个问题?

标签: javascriptmysqlnode.jshttp

解决方案


那应该很简单。

您只需要从您的请求中接收参数并将其附加到字符串。

这是您更新的代码。

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();   
   }
});

推荐阅读