Shopify GraphQL 使用 fetch API, returns empty json, 没有错误
Shopify GraphQL using fetch API, returns empty json, no errors
尝试使用 Shopify 的 Fetch API 和 GraphQL 端点在 React 组件中获取我的商店名称。
我创建了一个 Shopify 商店,授予 Storefront API 权限,并在我的 React 组件的 componentDidMount()
部分制作了它。
let query = '{ shop { name } }';
console.log(JSON.stringify(query));
fetch('https://myStoreName.myshopify.com/api/graphql', {
method: "POST",
headers: {
"Content-Type": "application/graphql",
"X-Shopify-Storefront-Access-Token": "<My API Key>"
},
body: JSON.stringify(query),
})
.then(function(myJson) {
console.log('fetched');
console.log(JSON.stringify(myJson));
});
我的控制台日志输出:
"{ shop { name } }"
App.js:21 fetched
App.js:22 {}
我什至没有收到错误,让我觉得它可能正在经历?
但是在此查询中找不到我的店铺名称?
我认为总的来说我不知道在 Javascript 中制作 GraphQL 查询的最佳实践。
我是制作一个大字符串还是只是一个普通的 JSON 来表示它?
*另外,我目前正在尝试不使用 graphQL 客户端库,而只是使用 fetch API。
您不能像那样直接读取 fetch
调用解析的响应。相反,您应该调用适合您正在获取的 MIME 类型的任何方法。来自 Mozilla 文档:
Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled.
对于JSON,你调用了json
方法。您可以查看更多示例 here。这意味着您的代码应该更像这样:
fetch(...)
.then(res => res.json())
.then(console.log)
此外,请记住您不需要 stringify
您的查询。您可能应该使用 application/json
内容类型(我相信这是标准的)并将您的查询包装在这样的对象中。
body: { query },
那么如果你有变量,这些可以包含在同一个对象中:
body: { query, variables }
尝试使用 Shopify 的 Fetch API 和 GraphQL 端点在 React 组件中获取我的商店名称。
我创建了一个 Shopify 商店,授予 Storefront API 权限,并在我的 React 组件的 componentDidMount()
部分制作了它。
let query = '{ shop { name } }';
console.log(JSON.stringify(query));
fetch('https://myStoreName.myshopify.com/api/graphql', {
method: "POST",
headers: {
"Content-Type": "application/graphql",
"X-Shopify-Storefront-Access-Token": "<My API Key>"
},
body: JSON.stringify(query),
})
.then(function(myJson) {
console.log('fetched');
console.log(JSON.stringify(myJson));
});
我的控制台日志输出:
"{ shop { name } }"
App.js:21 fetched
App.js:22 {}
我什至没有收到错误,让我觉得它可能正在经历? 但是在此查询中找不到我的店铺名称?
我认为总的来说我不知道在 Javascript 中制作 GraphQL 查询的最佳实践。 我是制作一个大字符串还是只是一个普通的 JSON 来表示它?
*另外,我目前正在尝试不使用 graphQL 客户端库,而只是使用 fetch API。
您不能像那样直接读取 fetch
调用解析的响应。相反,您应该调用适合您正在获取的 MIME 类型的任何方法。来自 Mozilla 文档:
Once a Response is retrieved, there are a number of methods available to define what the body content is and how it should be handled.
对于JSON,你调用了json
方法。您可以查看更多示例 here。这意味着您的代码应该更像这样:
fetch(...)
.then(res => res.json())
.then(console.log)
此外,请记住您不需要 stringify
您的查询。您可能应该使用 application/json
内容类型(我相信这是标准的)并将您的查询包装在这样的对象中。
body: { query },
那么如果你有变量,这些可以包含在同一个对象中:
body: { query, variables }