【问题标题】:Axios, Shopify Storefront API, "Parameters missing or invalid", "Parse error"Axios、Shopify Storefront API、“参数丢失或无效”、“解析错误”
【发布时间】:2021-11-03 00:50:00
【问题描述】:

我被困住了。我正在尝试从 Shopify 的 Storefront API 中检索数据。帖子请求在邮递员中工作正常。它们是 graphql http 请求。 here is a screenshot

所以我从邮递员应用程序中复制了 axios 代码,并将其粘贴到我的 React 应用程序中(这只是 react 和 shopify buy 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);
  });

this 是它返回的错误:状态 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,但没有商店名称。相反,我得到a parse error: "Parse error on "shop" (IDENTIFIER) at [2, 11]"。如果我将“Content-Type”标头更改为“application/graphql”,我会得到类似的parse error

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

【问题讨论】:

    标签: axios graphql shopify shopify-javascript-buy-sdk shopify-storefront-api


    【解决方案1】:

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

    其次,您对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 客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-07
      • 2020-10-11
      • 2023-03-31
      • 2018-08-04
      • 2016-02-19
      相关资源
      最近更新 更多