【问题标题】:creating DELETE request using nodejs on sql database在 sql 数据库上使用 nodejs 创建 DELETE 请求
【发布时间】:2019-04-21 06:41:06
【问题描述】:

node.js 的新手并学习如何将mysqlnode 一起使用。我有一个form.html,它有两个按钮可以输入department_nodepartment_name。我能够成功插入mysql 数据库,但我不知道如何删除特定的dept_no。我想要做的是输入dept_nodept_name,然后根据dept_no 从我的数据库中输入DELETE。我还希望能够检查用户输入的内容,以确保它是有效的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>

【问题讨论】:

  • 改用const queryString = "DELETE FROM departments WHERE dept_no = ?";
  • 但是我如何使用form 并将信息传递到form 并根据我的database 中的信息删除
  • 这篇文章没有解释如何通过@Barns 使用 express 从 mysql 数据库中删除
  • 您可以使用 sequelizejs (ORM) docs.sequelizejs.com 来执行节点数据库操作。这将使您轻松执行 CRUD 操作。

标签: mysql node.js express


【解决方案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
  });
});

【讨论】:

    【解决方案2】:

    HTML 表单通常不支持DELETE 请求。 Node 应用程序可以使用像这样的解决方法 - https://github.com/expressjs/method-override

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 2022-11-02
      • 2018-02-19
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 2019-06-03
      • 2014-07-27
      相关资源
      最近更新 更多