簡體   English   中英

DELETE 用戶 Express 端可以工作,但不能使其在前端工作(使用 React)

[英]DELETE user Express side works, but can't make it work on front-end side (using React)

我在服務器端(Express)創建了我的路由用戶/刪除,我通過 Postman 進行了測試,並且沒有任何問題,但不知何故我無法讓它在前端工作。

這是我的反應代碼,我正在嘗試創建 function 使用 axios 從快遞中刪除和獲取路線:

  const handleDelete = () => {
    axios
      .delete("http://localhost:9090/users/delete", {})
      .then(response => response.data)
      .catch(error => {
        throw error.response.data;
      });
  };

以下是我使用 function 的方式:

  <button type="button" onClick={handleDelete}>
    Delete your account
  </button>
</div>

我還是這項技術的新手,所以我不確定什么是正確的方法。

您應該像這樣使您的后端(快速)刪除路線: /users/:userId
刪除某個用戶需要用戶 ID。

然后你可以在前端這樣做:

async function deleteUser(userId) {
  try {
    const request = await axios.delete(`http://localhost:9090/users/${userId}`)
    console.log("deleted")
  } catch(err) {
    console.log(err)
  }
}

您的 controller:

router.delete("/users/delete/:userId", isAuthenticated, async (req, res, next) => {
    const { userId } = req.params
    try {
        const user = await User.query().findById(userId).throwIfNotFound()
        await user.$query().delete()
        res.json(user)
    } catch (err) {
        next(err)
    }
})

查看評論,我相信問題可能出在您正在使用的isAuthenticated中間件上,因為當身份驗證中間件失敗時,它會引發403 Forbidden錯誤。 您可能需要傳遞一些令牌,以便在axios調用中驗證您的請求。

const request = await axios.delete(`http://localhost:9090/users/${userId}`,{header})

如果您可以提供有關中間件的更多信息,我將更新我的答案。

暫無
暫無

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

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