From my frontend, I’m trying to get products with Admin API(GraphQL) from Shopify with the code below:
*I used "axios" on Quasar Framework and this is Headless Commerce
const response = await this.$axios({
url: "https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json",
method: 'POST',
headers: {
"X-Shopify-Access-Token": "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"
},
data: {
"query": `
{
products(first: 5) {
edges {
node {
id
title
}
}
}
}
`
}
});
console.log(response.data);
But I got this error as shown below:
Access to XMLHttpRequest at
‘https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json’
from origin ‘http://localhost:8080’
has been blocked by CORS policy: Response to preflight request doesn’t
pass access control check: No ‘Access-Control-Allow-Origin’ header is
present on the requested resource.
So next, I added the header "Access-Control-Allow-Origin": "*" and "Content-Type": "application/json" as shown below:
const response = await this.$axios({
url: "https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json",
method: 'POST',
headers: {
"X-Shopify-Access-Token": "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",
"Access-Control-Allow-Origin" : "*", // Here
"Content-Type": "application/json" // Here
},
data: {
"query": `
{
products(first: 5) {
edges {
node {
id
title
}
}
}
}
`
}
});
console.log(response.data);
But I still get the same error:
Access to XMLHttpRequest at
‘https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json’
from origin ‘http://localhost:8080’
has been blocked by CORS policy: Response to preflight request doesn’t
pass access control check: No ‘Access-Control-Allow-Origin’ header is
present on the requested resource.
Are there any ways to solve the error?
2
Answers
You cannot use Admin API from your frontend to get products from Shopify. Only Storefront API is available from your frontend so replace the url with:
Then, replace the header "X-Shopify-Access-Token" with "X-Shopify-Storefront-Access-Token" as shown below:
Finally, for headers, only "X-Shopify-Storefront-Access-Token" is enough so you don't need "Access-Control-Allow-Origin": "*" and "Content-Type": "application/json".
This is the full code which works:
You can refer to the documentation.
Admin API is only allowed to use with admin api token.
You can only access to store front api in your theme.