【发布时间】:2022-10-20 21:40:14
【问题描述】:
我正在尝试从 shopify API 获取产品,但不明白为什么它会在我的 catch 语句中抛出一个错误集。错误说
error - utils/fetchShop.js (28:10) @ productData
Error: Products not fetched
26 | return data;
27 | } catch (error) {
> 28 | throw new Error('Products not fetched');
| ^
29 | }
30 | }
你能帮我弄清楚我在这里做错了什么吗?所以基本上我是
- 创建一个名为 productData 的函数来接受查询。
- productData 它将使用设置的标头向 Shopify Storefront GraphQL API 发出 POST 请求并返回 json 响应。
- productData 函数会将数据返回给 getAllProducts 函数,该函数会将其设置为等于 allProducts 变量。
这是我的代码:
const domain = process.env.SHOPIFY_STOREFRONT_DOMAIN; const storefrontAccessToken = process.env.SHOPIFY_STOREFRONT_ACCESS_TOKEN; async function productData(query) { const URL = `https://${domain}/api/2022-04/graphql.json`; const options = { endpoint: URL, method: 'POST', headers: { 'X-Shopify-Storefront-Access-Token': storefrontAccessToken, Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query }), }; try { const data = await fetch(URL, options).then((response) => { return response.json(); }); return data; } catch (error) { throw new Error('Products not fetched'); } } export async function getAllProducts() { const query = `{ products(first: 250) { edges { node { handle id } } } }`; const response = await productData(query); const slugs = response.data.products.edges ? response.data.products.edges : []; return slugs; }
【问题讨论】:
-
catch块中的error对象中有什么? -
@Aseem Gautam - 它在控制台中显示:``` FetchError: request to https//spnsors.myshopify.com/api/2022-04/graphql.json failed, reason: getaddrinfo ENOTFOUND https at ClientRequest.<anonymous> (/Users/blkboxng/Desktop/publicTradesProperties/spnsors/node_modules/next/dist /compiled/node-fetch/index.js:1:64142) errno: 'ENOTFOUND', 代码: 'ENOTFOUND' } ```
-
问题中的网址是正确的。这里是缺少的
:、https//。 -
@AseemGautam - 感谢您的回复。您是正确的,我之前对您的回复中缺少
:,但它包含在保存为URL变量的实际代码中,如上所示。 -
您能否成功向应用程序外部的店面 URL 发出请求(例如来自 Postman)?