Hello,
*Note: when I say metafield I mean a metafield created in Admin>Settings>Metafields
I’ve been trying to show nutritional info for a selected product that is included in a pack. The goal is to select a flavor from the options rendered by liquid, fetch the metafield data of the given product and then display it without reloading the page.
I see that it’s not possible to retrieve metafield data for a product via the storefront API, not sure why because that would make this 1000% easier.
Here is the liquid for the dropdown:
Here is the js running the logic behind the dropdown:
window.addEventListener('DOMContentLoaded', function() {
setActiveSelectContainer('#multi-flav-select', '.dropdown-item');
});
function setActiveSelectContainer(containerSelector, subItemSelector) {
let container = document.querySelector(containerSelector);
let subItems = container.querySelectorAll(subItemSelector);
for (var i = 0; i < subItems.length; i++) {
subItems[i].addEventListener("click", function() {
var current = document.querySelectorAll(".dropdown-item.active");
if(current.length > 0) {
current[0].className = current[0].className.replace(" active", "");
}
this.className += " active";
setFlavorInfo(this.innerText, this.dataset.handle);
});
}
}
function setFlavorInfo(currentFlavor, productHandle) {
let flvLabel = document.querySelector('#flavor-label');
flvLabel.innerText = currentFlavor;
console.log("Current Product: " + currentFlavor + " | Product Data Handle:" + productHandle);
/* grab flavor info async then display it on successful response */
const shopURL = '{{ shop.url }}';
const urlForID = shopURL + '/products/' + productHandle + '.json';
fetch(urlForID)
.then(response => response.json())
.then(function(data) {
console.log(" --Product ID: " + data.product.id);
getMetaFields(data.product.id);
})
.catch(err => console.log(err));
}
function getMetaFields(productID) {
const shopURL = '{{ shop.url }}';
const urlForMeta = shopURL + '/admin/products/' + productID + '/metafields.json';
fetch(urlForMeta)
.then(response => response.json())
.then(function(data) {
console.log(" --Product Metafields: " + data);
})
.catch(err => console.log(err))
}
I seem to be getting a CORS error on the second fetch request and I’m now wondering this: “Do I really have to create a private app to simply fetch metafields?”
Or am I approaching this wrong and there is another way to do this without creating an app?
The exact errors are as follow:
-TypeError: NetworkError when attempting to fetch resource.
-Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-store.com/admin/products/3486492852299/metafields.json . (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 401.