client side傳遞方式

// ejs
<button type="button" onclick="deleteProduct('<%= product._id %>', '<%= csrfToken %>')">删除产品</button>

<script src="/js/admin.js"></script>

有在app.js讀取靜態資源才能在ejs模板中直接載入

// app.js
// 讀取靜態資源目錄
app.use(express.static(path.join(__dirname, "public")));
// public/js/admin.js
const deleteProduct = (productId, csrfToken) => {

  fetch("/admin/product/" + productId, {
    method: "DELETE",
    headers: {
      "csrf-token": csrfToken,
    },
  })
    .then((result) => {
      return result.json()
    })
    .then((data) => {
			// 添加刪除操作
      if (data.message === "success") {
				const productElement = event.target.closest(".p-2");
				const productParentElement = productElement.parentNode;
				productParentElement.removeChild(productElement);
			}
    })
    .catch((err) => {
      console.log("刪除錯誤", err);
    });
};

截圖 2021-09-06 下午2.30.33.png

// routes/admin.js
router.delete("/product/:productId", isAuth, adminController.deleteProduct);
// controllers/admin.js
exports.deleteProduct = (req, res, next) => {
  const productId = req.params.productId;

  Product.findById(productId)
    .then((product) => {
      // 判斷是否有產品 在刪除圖片
      if (!product) {
        next(new Error("未找到產品"));
      }

      fileHelper.deleteFile(product.imageUrl);
      // 產品及用戶ID都匹配才能刪除
      return Product.deleteOne({ _id: productId, userId: req.user._id });
    })
    .then((result) => {
      res.json({ message: "success", ...result });
    })
    .catch((err) => {
      res.json({ message: "fail" });
    });
};