在SQL数据库上使用Node.js创建DELETE请求

时间:2018-11-18 21:19:57

标签: mysql node.js express

node.js的新手,并学习如何将mysqlnode一起使用。我有一个form.html,它有两个按钮来输入department_nodepartment_name。我可以成功插入mysql数据库,但是不知道如何删除特定的dept_no。我要执行的操作是输入dept_nodept_name,然后根据DELETE从我的数据库中输入dept_no。另外,我希望能够检查用户输入的内容,以确保它是有效的dept_nodept_name。任何有关如何入门或研究如何做到这一点的想法都将非常有帮助。我将在下方粘贴我的node.jsform.html

node.js

// DELETE BELOW
app.delete("/deleteEmp/", (req, res) => {
  console.log("Department number is " + req.body.department_no);
  console.log("Department name is " + req.body.department_name);

  const deptNumber = req.body.department_no;
  const deptName = req.body.department_name;

  const connection = mysql.createConnection({
    host: "localhost",
    user: "root",
    database: "employees"
  });

  const queryString = "DELETE departments WHERE dept_no = ?";
  connection.query(queryString, [department_no], (err, results, fields) => {
    if (err) {
      console.log("Could not delete" + err);
      res.sendStatus(500);
      return;
    }
    console.log("Deleted department_no with dept_name");
    res.end();
  });
});

form.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>SQLFORM</title>
    <style>
      #space {
        margin-top: 20px;
      }
    </style>
  </head>
  <body>
    <div>Fill Form Below</div>
    <hr />
    <div id="space">
      <form action="/deleteEmp" method="DELETE">
        <input placeholder="Enter Department Number" name="department_no" />
        <input placeholder="Enter Department Name" name="department_name" />
        <button>Submit</button>
      </form>
    </div>
  </body>
</html>

2 个答案:

答案 0 :(得分:1)

HTML表单通常不支持DELETE请求。节点应用可以使用类似的变通方法-https://github.com/expressjs/method-override

答案 1 :(得分:1)

另一种替代方法是执行对允许的方法没有限制的AJAX请求。简化示例:

document.querySelector('#space form').addEventListener('submit', (event) => {
  event.preventDefault();

  let formData = new FormData();
  formData.append('department_no', document.querySelector("input[name='department_no']").value);
  formData.append('department_name', document.querySelector("input[name='department_name']").value);

  fetch('https://yoururl.com/deleteEmp', {
    method: 'DELETE',
    headers: {
      "Content-type": "application/x-form-urlencoded"
    },
    body: formData
  });
});