[英]TypeError: Cannot read property 'price' of undefined
我正在創建一個在線商店來學習node.js。 當我從products.json文件刪除產品時,cart.json中的相應產品也會被刪除。 嘗試刪除產品時,圖片中出現以下錯誤。 這是代碼!
在products.ejs中
<form action="/admin/delete-product" method="POST">
<input type="hidden" name="productId" value="<%=product.id%>">
<button class="btn" type="submit">Delete</button>
</form>
鏈接控制器后,在控制器功能中,在admin.js控制器中,
// import product model
const Product = require('../models/product');
// delete a product
exports.postDeleteProduct = (req, res) => {
const prodId = req.body.productId;
Product.deleteById(prodId, () => {
res.redirect('/admin/products');
});
}
然后在product.js模型中
// import cart model
const Cart = require('./cart');
// get all the products from the file
const getProductsFromFile = cb => {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
} else {
cb(JSON.parse(fileContent));
}
});
};
// delete by id
static deleteById(id, callback) {
getProductsFromFile(products => {
const product = products.find(prod => prod.id == id);
const updatedProducts = products.filter(prod => prod.id !== id);
fs.writeFile(p, JSON.stringify(updatedProducts), err => {
if (!err) {
console.log('Product: ',product);
//also delete in the cart
Cart.deleteProduct(id, product.price, callback);
}
})
})
}
執行代碼后,出現以下錯誤。 注意,“產品”有兩個控制台輸出。 一個用於實際產品,第二個由於某種原因undefined
!
static deleteById(id, callback) {
console.log('deleteById', { id });
getProductsFromFile(products => {
let deletedProduct = null;
let updatedProducts = [];
for(const product of products) {
if(product.id === id) {
deletedProduct = product
} else {
updatedProducts.push(product);
}
}
if (!deletedProduct) {
console.log('deleteById: Product not found', { id });
callback();
} else {
fs.writeFile(p, JSON.stringify(updatedProducts), err => {
if (!err) {
console.log('deleteById: Product', deletedProduct);
Cart.deleteProduct(id, deletedProduct.price, callback);
}
});
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.