-2

我被困住了。我正在尝试从 Shopify 的 Storefront API 中检索数据。帖子请求在邮递员中工作正常。它们是 graphql http 请求。这是一个截图

所以我从邮递员应用程序中复制了 axios 代码,并将其粘贴到我的 React 应用程序中(这只是反应和 shopify 购买 sdk)。这是我的代码:

var data = JSON.stringify({
    query: `query {     
      shop {
          name
      }
  }`,
    variables: {}
  });

  var config = {
    method: 'post',
    url: 'https://<shop name>.myshopify.com/api/2021-07/graphql.json',
    headers: { 
      'X-Shopify-Storefront-Access-Token': '<access token>', 
      'Content-Type': 'application/json'
    },
    data : data
  };

  axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error.response);
  });

这是返回的错误:状态 400,“参数丢失或无效”。所以我尝试了这样的事情:

const url = 'https://<shop-name>.myshopify.com/api/2021-07/graphql.json'
  const headers = {
    'X-Shopify-Storefront-Access-Token': '<access token>',
    'Content-Type': 'application/json',
  }

await axios.post(
    url, // this is the same as the previous url
    {query: `
      shop {
        name
      }
    `},
    {headers: headers}) // headers are the same as previous headers
  .then((result) => console.log(result))
  .catch((error) => {
      console.log(error.response);
  });

我现在得到一个状态 200,但没有商店名称。相反,我收到一个解析错误:“[2, 11] 处的“商店”(IDENTIFIER)上的解析错误”。如果我将“Content-Type”标头更改为“application/graphql”,我会收到类似的解析错误

请帮忙。我不知道如何让它工作。提前致谢。

4

1 回答 1

0

首先,您必须了解来自 graphql 的错误代码。成功时,graphql 端点始终返回 200 POST,但通过解析您的请求仍然可能存在嵌套错误。

其次,您的查询TypedStringArray缺少query. 它应该看起来像

const url = 'https://<shop-name>.myshopify.com/api/2021-07/graphql.json'
  const headers = {
    'X-Shopify-Storefront-Access-Token': '<access token>',
    'Content-Type': 'application/json',
  }

await axios.post(
    url, // this is the same as the previous url
    {data : {
       query: `
         query GiveMeMyShop {
           shop {
             name
         }
       }
    `},
    {headers: headers}) // headers are the same as previous headers
  .then((result) => console.log(result))
  .catch((error) => {
      console.log(error.response);
  });

获取正确的查询语法。但在所有情况下,我都建议使用像 apollo 这样的 gql 客户端。

于 2021-09-06T06:54:35.903 回答