從我的前端,我正在嘗試使用以下代碼從Shopify獲取具有Admin API(GraphQL)的產品:
*我在 Quasar Framework 上使用了“axios”,這是 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);
但是我得到了這個錯誤,如下所示:
從源“http://localhost:8080”訪問“https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json”的 XMLHttpRequest 已被 CORS 策略阻止:對預檢的回應請求未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。
所以接下來,我添加了標題“Access-Control-Allow-Origin”:“*”和“Content-Type”:“application/json”,如下所示:
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);
但我仍然得到同樣的錯誤:
從源“http://localhost:8080”訪問“https://healthy-food.myshopify.com/admin/api/2022-01/graphql.json”的 XMLHttpRequest 已被 CORS 策略阻止:對預檢的回應請求未通過訪問控制檢查:請求的資源上不存在“Access-Control-Allow-Origin”標頭。
有什么方法可以解決錯誤嗎?
uj5u.com熱心網友回復:
您無法使用管理員API從您的前端以獲得產品Shopify。只有店面API可從您的前端因此與更換網址:
// "/admin" is removed
"https://healthy-food.myshopify.com/api/2022-01/graphql.json"
然后,將標題“X-Shopify-Access-Token”替換為“X-Shopify-Storefront-Access-Token”,如下所示:
"X-Shopify-Storefront-Access-Token": "yourStorefrontAccessToken"
最后,對于標題,只有"X-Shopify-Storefront-Access-Token"就足夠了,所以你不需要 "Access-Control-Allow-Origin": "*"和"Content-Type": "application/json" .
這是有效的完整代碼:
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);
您可以參考檔案。
uj5u.com熱心網友回復:
Admin API只允許與 admin api token 一起使用。
您只能在您的主題中訪問 store front api。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406897.html
標籤:
