我正在设计一个自定义产品构建器,但在将商品添加到购物车时遇到问题。
代码查找“单击”项目的product.id,然后将其推送到我的有效负载/表单对象。当我运行 console.log 时,我看到了所有 id,但 fetch 无法识别它们,所以我收到错误:
{status: 404, message: "Cart Error", description: "Cannot find variant"}
description: "Cannot find variant"
message: "Cart Error"
status: 404
这是添加到购物车功能
document.getElementById('add-to-cart-button').addEventListener('click', async function(event) {
event.preventDefault();
console.log("Add-to-cart button clicked.");
let form = {
items: []
};
let selectedOption = necklaceVariantDropdown.options[necklaceVariantDropdown.selectedIndex];
let selectedNecklaceVariantId = parseInt(selectedOption.getAttribute('data-id'), 10);
if (!selectedNecklaceVariantId) {
console.warn("No necklace variant selected.");
return;
}
form.items.push({
id: selectedNecklaceVariantId,
quantity: 1
});
console.log("Necklace variant added to cart items:", selectedNecklaceVariantId);
let selectedCharms = necklacePreview.querySelectorAll('.charm-item.cloned');
console.log(`Found ${selectedCharms.length} selected charms.`);
//Add each selected charm to the cart items array
selectedCharms.forEach(charm => {
let charmId = parseInt(charm.getAttribute('data-id'), 10);
if (!charmId) {
console.warn("Charm with no data-id found:", charm);
return;
}
form.items.push({
id: charmId,
quantity: 1
});
console.log(`Charm with ID ${charmId} added to cart items.`);
});
if (form.items.length === 0) {
console.warn("No items to add to the cart.");
return;
}
console.log("All cart items ready to be added:", form.items);
// Sending all items together
await fetch(window.Shopify.routes.root + 'cart/add.js', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(form)
})
.then(response => {
if (!response.ok) {
throw new Error(`Server responded with status: ${response.statusText}`);
}
return response.json();
})
.catch((error) => {
console.error('Error:', error);
});
});
这是我的控制台:
Necklace variant added to cart items: 45484000182550
scripts.js?567:100 Found 3 selected charms.
scripts.js?567:114 Charm with ID 8768164200726 added to cart items.
scripts.js?567:114 Charm with ID 8483792650518 added to cart items.
scripts.js?567:114 Charm with ID 8523530764566 added to cart items.
scripts.js?567:122 All cart items ready to be added: (4) [{…}, {…}, {…}, {…}]
这是请求负载
[
{
"id": 45484000182550,
"quantity": 1
},
{
"id": 8768164200726,
"quantity": 1
},
{
"id": 8483792650518,
"quantity": 1
},
{
"id": 8523530764566,
"quantity": 1
}
]
您收到此错误是因为根据 Shopify 文档
id
仅接受变体 ID,而不接受产品 ID。
您提到您通过
product.id
获取点击的项目 ID,但您应该引用 variant.id
。您可以循环遍历 product.variants
来获取产品的所有 variant.id
并将它们分配给您的 data-id
属性。
查看以下 Liquid API,了解有关产品和变体属性的更多信息: