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?
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:
// "/admin" is removed
"https://healthy-food.myshopify.com/api/2022-01/graphql.json"
Then, replace the header "X-Shopify-Access-Token" with "X-Shopify-Storefront-Access-Token" as shown below:
"X-Shopify-Storefront-Access-Token": "yourStorefrontAccessToken"
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:
const response = await this.$axios({ // "/admin" is removed
url: "https://healthy-food.myshopify.com/api/2022-01/graphql.json",
method: 'POST',
headers: {
"X-Shopify-Storefront-Access-Token": "yourStorefrontAccessToken"
// "X-Shopify-Access-Token" is replaced with "X-Shopify-Storefront-Access-Token"
},
data: {
"query": `
{
products(first: 5) {
edges {
node {
id
title
}
}
}
}
`
}
});
console.log(response.data);
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.