I’m trying to make my own private/custom app from my Admin area. At the moment I’m just testing whether I can return a list of products to the console. First I tried using the JS Buy SDK, I pasted this code in to the Product page template but it does not work:
// Build a custom products query using the unoptimized version of the SDK
const productsQuery = client.graphQLClient.query((root) => {
root.addConnection('products', {args: {first: 10}}, (product) => {
product.add('title');
product.add('tags');// Add fields to be returned
});
});
// Call the send method with the custom products query
client.graphQLClient.send(productsQuery).then(({model, data}) => {
// Do something with the products
console.log(model);
});
I’ve also tried querying the GraphQL:
const productQuery = () => `
query {
shop {
products( first: 10) {
edges{
node {
id
handle
title
variants(first: 10){
edges{
node{
title
}
}
}
}
}
}
}
}
`;
const STOREFRONT_ACCESS_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
const GRAPHQL_URL = 'https://teststore.myshopify.com/api/2021-10/graphql.json'
const GRAPHQL_BODY = () => {
return {
'async': true,
'crossDomain': true,
'method': 'POST',
'headers': {
'X-Shopify-Storefront-Access-Token': STOREFRONT_ACCESS_TOKEN,
'Content-Type': 'application/graphql',
},
'body': productQuery()
};
}
fetch(GRAPHQL_URL, GRAPHQL_BODY())
.then(res => res.json())
.then(products => {
console.log('products', products)
});
This also does not work. I get the following error:
Access to fetch at 'https://teststore.myshopify.com/api/2021-10/graphql.json' from origin 'https://teststore.myshopify.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Can someone please advise?