簡體   English   中英

使用 Fetch 刪除用戶端點

[英]Delete user endpoint using Fetch

我正在建立一個用戶網站,管理員應該可以在其中刪除用戶。 我的項目是使用 Azure SQL 數據庫構建的。 我在我的控制器文件中提出了一個端點 deleteUser

刪除用戶

const deleteUser = (req, res) => {
  sql.connect(config, function (err) {
    if (err) console.log(err);
    // create Request object
    var request = new sql.Request();
    // query to the database and get the records

    const { id } = req.query

    request.query(
      `DELETE FROM users where User_ID = '${id}'`,
      function (err, recordset) {
        if (err) {
          console.log(err);
        } else if (!id) {
          res.json("Please provide an ID")
        } else {
          res.json(`User with ID: ${id} has been deleted!`)
        }
      }
    );
  });
};

然后我嘗試使用 fetch 和 EJS 調用這個端點。

我在 EJS 腳本標簽中的代碼

<script>

document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {

    e.preventDefault();

    fetch('http://localhost:3000/deleteUser', {
    method:'DELETE',
    headers: {
        "Content-Type": "application/json",
      },
      body: null
    })
    .then((response) => console.log(response))
    .catch((e) => {
        console.log(e)
    })
})
</script>

我控制台記錄響應,所以路由一定是好的,但它似乎沒有將 ID 解析到提取中。 處理這個問題的正確方法是什么?

提前致謝!

解決方案

我提出了以下解決方案 - 這不是最好的,但有效。

document.getElementById('deleteUserBtn').addEventListener('submit', (e) => {

    e.preventDefault();

    // delete user using fetch

    const id = document.getElementById('userId').textContent

    fetch(`http://localhost:3000/deleteUser?id=${id}`, {
    method:'DELETE',
    headers: {
        "Content-Type": "application/json",
      },
      body: null
    })
    .then((response) => console.log(response))
    .catch((e) => {
        console.log(e)
    })
})

感謝您的貢獻!

id 不應該在 fetch 請求的 URL 中嗎? 您要從請求參數中獲取 id,因此它可能應該附加到路徑中,例如

const id = wherever your id comes from; 

fetch('http://localhost:3000/deleteUser?id=${id}...'

您還需要在按鈕方法中獲取用戶 ID,但需要更多代碼才能查看它的來源。

通常使用 ID 進行刪除是最好的方法

fetch('http://localhost:3000/deleteUser/:id...'

但是,您可以在正文、參數、查詢甚至標頭中以任何方式傳遞 id)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM