类型错误:无法读取 C:\NODEJS-COMPLETE-GUIDE\controllers\shop.js:45:37 处未定义的属性"price"



我试图将我的产品添加到购物车中,并试图获得totalPrice,但它显示了错误。这是我的错误:-在此处输入图像描述。这里,是我商店的代码。js:-

exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId, product => {
Cart.addProduct(prodId, product.price);
});
res.redirect('/cart');
};

这里,是cart.js文件的代码:-

const fs = require('fs');
const path = require('path');
const p = path.join(
path.dirname(process.mainModule.filename),
'data',
'cart.json'
);
module.exports = class Cart {
static addProduct(id, productPrice) {
// Fetch the previous cart
fs.readFile(p, (err, fileContent) => {
let cart = { products: [], totalPrice: 0 };
if (!err) {
cart = JSON.parse(fileContent);
}
// Analyze the cart => Find existing product
const existingProductIndex = cart.products.findIndex(
prod => prod.id === id
);
const existingProduct = cart.products[existingProductIndex];
let updatedProduct;
// Add new product/ increase quantity
if (existingProduct) {
updatedProduct = { ...existingProduct };
updatedProduct.qty = updatedProduct.qty + 1;
cart.products = [...cart.products];
cart.products[existingProductIndex] = updatedProduct;
} else {
updatedProduct = { id: id, qty: 1 };
cart.products = [...cart.products, updatedProduct];
}
cart.totalPrice = cart.totalPrice + +productPrice;
fs.writeFile(p, JSON.stringify(cart), err => {
console.log(err);
});
});
}
};

这里,是product.js文件的代码:-

const fs = require('fs');
const path = require('path');
const p = path.join(
path.dirname(process.mainModule.filename),
'data',
'products.json'
);
const getProductsFromFile = cb => {
fs.readFile(p, (err, fileContent) => {
if (err) {
cb([]);
} else {
cb(JSON.parse(fileContent));
}
});
};
module.exports = class Product {
constructor(title, imageUrl, description, price) {
this.title = title;
this.imageUrl = imageUrl;
this.description = description;
this.price = price;
}
save() {
this.id = Math.random().toString();
getProductsFromFile(products => {
products.push(this);
fs.writeFile(p, JSON.stringify(products), err => {
console.log(err);
});
});
}
static fetchAll(cb) {
getProductsFromFile(cb);
}
static findById(id, cb) {
getProductsFromFile(products => {
const product = products.find(p => p.id === id);
cb(product);
});
}
};

如果我从shop.js文件中删除product.price,它不会给我错误,但当我添加价格时,它会给我错误。

看起来您正在尝试将findById方法找不到的产品添加到购物车中。只需在回调中添加if条件即可验证搜索结果。

exports.postCart = (req, res, next) => {
const prodId = req.body.productId;
Product.findById(prodId, product => {
if (product) {    
Cart.addProduct(prodId, product.price);
} else {
// log error or warn user
}
});
res.redirect('/cart');
};

最新更新