【问题标题】:gatsby-source-graphql and GraphQL Shopify Admin API errorgatsby-source-graphql 和 GraphQL Shopify 管理 API 错误
【发布时间】:2019-09-29 11:04:24
【问题描述】:

可以找到带有此代码的 repo HERE

我正致力于从 Shopify Storefront 和 GraphQL Admin API 中获取数据并将其合并到 Gatsby 中。对于采购 Storefront API,我使用 gatsby-source-shopify,但我无法找到 Shopify Admin API 的源插件,最终使用了 gatsby-source-graphql。

我创建了一个 private Shopify app 并授予了所有权限,并且能够使用 Shopify GraphQL Admin API 文档中的 curl 示例获取数据。

curl -X POST \
"https://shop-name.myshopify.com/admin/api/2019-04/graphql.json" \
-H "Content-Type: application/graphql" \
-H "X-Shopify-Access-Token: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
-d '
{
  shop {
    name
  }
}
'

输出:

{"data":{"shop":{"name":"Shop Name"}},"extensions":{"cost":{"requestedQueryCost":1,"actualQueryCost":1,"throttleStatus":{"maximumAvailable":1000.0,"currentlyAvailable":999,"restoreRate":50.0}}}}

错误信息:

success open and validate gatsby-configs — 0.007 s
success load plugins — 0.345 s
success onPreInit — 0.005 s
success initialize cache — 0.015 s
success copy gatsby files — 0.068 s
success onPreBootstrap — 0.006 s
error Plugin gatsby-source-graphql returned an error


  Error: Parse error on "operationName" (STRING) at [1, 2]


gatsby-source-shopify/sandbox starting to fetch data from Shopify

gatsby-source-shopify/sandbox fetched and processed productTypes: 287.590ms

gatsby-source-shopify/sandbox fetched and processed policies: 297.440ms

gatsby-source-shopify/sandbox fetched and processed blogs: 302.418ms

gatsby-source-shopify/sandbox fetched and processed articles: 344.917ms

gatsby-source-shopify/sandbox fetched and processed collections: 8603.841ms


gatsby-source-shopify/sandbox fetched and processed products: 20362.561ms

gatsby-source-shopify/sandbox finished fetching data from Shopify: 20369.525ms
warning The gatsby-source-graphql plugin has generated no Gatsby nodes. Do you need it?
success source and transform nodes — 21.169 s
warning Multiple node fields resolve to the same GraphQL field `ShopifyArticle.blog` - [`blog`, `blog___NODE`]. Gatsby will use `blog___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyCollection.products` - [`products`, `products___NODE`]. Gatsby will use `products___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.options` - [`options`, `options___NODE`]. Gatsby will use `options___NODE`.
warning Multiple node fields resolve to the same GraphQL field `ShopifyProduct.variants` - [`variants`, `variants___NODE`]. Gatsby will use `variants___NODE`.
success building schema — 0.283 s
success createPages — 0.000 s
success createPagesStatefully — 0.042 s
success onPreExtractQueries — 0.005 s
success update schema — 0.019 s
success extract queries from components — 0.098 s
success run static queries — 0.021 s — 2/2 96.96 queries/second
success run page queries — 0.014 s — 4/4 301.32 queries/second
success write out page data — 0.012 s
success write out redirect data — 0.001 s
success Build manifest and related icons — 0.104 s
success onPostBootstrap — 0.106 s

info bootstrap finished - 23.946 s

 WARNING  Compiled with 1 warnings                                                         6:04:43 PM

Module Warning (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  2:10  warning  'useStaticQuery' is defined but never used  no-unused-vars
  2:26  warning  'graphql' is defined but never used         no-unused-vars

✖ 2 problems (0 errors, 2 warnings)


You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.

You can now view gatsby-shopify in the browser.

  http://localhost:8000/

View GraphiQL, an in-browser IDE, to explore your site's data and schema

  http://localhost:8000/___graphql

Note that the development build is not optimized.
To create a production build, use npm run build

warning ⚠ 「wdm」:
info ℹ 「wdm」: Compiled with warnings.
 WAIT  Compiling...                                                                        6:04:43 PM

info ℹ 「wdm」: Compiling...
 WARNING  Compiled with 1 warnings                                                         6:04:43 PM

Module Warning (from ./node_modules/eslint-loader/index.js):

/Users/skok/dev/gatsby-shopify-starter/src/components/collections.js
  2:10  warning  'useStaticQuery' is defined but never used  no-unused-vars
  2:26  warning  'graphql' is defined but never used         no-unused-vars

✖ 2 problems (0 errors, 2 warnings)


You may use special comments to disable some warnings.
Use // eslint-disable-next-line to ignore the next line.
Use /* eslint-disable */ to ignore all warnings in a file.
warning ⚠ 「wdm」:
info ℹ 「wdm」: Compiled with warnings.

gatsby-config.js:

require('dotenv').config({
  path: `.env.${process.env.NODE_ENV}`
});

module.exports = {
  siteMetadata: {
    title: `Gatsby Shopify`,
    description: `Gatsby Shopify Starter.`,
    author: `@iamskok`,
  },
  plugins: [
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: "gatsby-source-graphql",
      options: {
        // This type will contain remote schema Query type
        typeName: "ShopifyAdmin",
        // This is field under which it's accessible
        fieldName: "admin",
        // Url to query from
        url: `https://${process.env.SHOP_NAME}.myshopify.com/admin/api/2019-04/graphql.json`,
        headers: {
          // Learn about environment variables: https://gatsby.dev/env-vars
          'X-Shopify-Access-Token': `${process.env.ADMIN_PASSWORD}`,
          'Content-Type': 'application/graphql'
        },
        fetchOptions: {
          method: 'POST'
        },
        refetchInterval: 60
      },
    },
    {
      resolve: `gatsby-source-shopify`,
      options: {
        // The domain name of your Shopify shop. This is required.
        // Example: 'gatsby-source-shopify-test-shop' if your Shopify address is
        // 'gatsby-source-shopify-test-shop.myshopify.com'.
        shopName: process.env.SHOP_NAME,

        // An API access token to your Shopify shop. This is required.
        // You can generate an access token in the "Manage private apps" section
        // of your shop's Apps settings. In the Storefront API section, be sure
        // to select "Allow this app to access your storefront data using the
        // Storefront API".
        // See: https://help.shopify.com/api/custom-storefronts/storefront-api/getting-started#authentication
        accessToken: process.env.STOREFRONT_ACCESS_TOKEN,

        // Set verbose to true to display a verbose output on `npm run develop`
        // or `npm run build`. This prints which nodes are being fetched and how
        // much time was required to fetch and process the data.
        // Defaults to true.
        verbose: true,
      },
    },
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
  ],
}

./src/collections.js:

import React from 'react'
import { useStaticQuery, graphql } from 'gatsby'

const Collections = () => {
  const storefrontData = useStaticQuery(
    graphql`
      query {
        allShopifyCollection {
          edges {
            node {
              id
              description
              descriptionHtml
              handle
              image {
                altText
                id
                src
                localFile {
                  childImageSharp {
                    fluid(maxWidth: 910) {
                      ...GatsbyImageSharpFluid_withWebp_tracedSVG
                    }
                  }
                }
              }
              products {
                id
                handle
                title
              }
              title
              updatedAt
            }
          }
        }
      }
    `
  )

  const adminData = useStaticQuery(
    graphql`
      query {
        admin {
          shop {
            name
          }
        }
      }
    `
  )

  console.log('storefront data:', JSON.stringify(storefrontData));
  console.log('admin data:', JSON.stringify(adminData));

  return (
    <div className="collections">
      <h2>Collections</h2>
    </div>
  )
}

export default Collections

index.js:

import React from 'react'
import Layout from '../components/layout'
import Collections from '../components/collections'

const IndexPage = () => (
  <Layout>
    <h1>Shopify</h1>
    <Collections />
  </Layout>
)

export default IndexPage

package.json:

{
  "name": "gatsby-shopify",
  "private": true,
  "description": "Gatsby Shopify Starter",
  "version": "0.1.0",
  "author": "Vladimir Skok <skok@vova.io>",
  "dependencies": {
    "gatsby": "^2.4.2",
    "gatsby-image": "^2.0.41",
    "gatsby-plugin-manifest": "^2.1.1",
    "gatsby-plugin-offline": "^2.1.0",
    "gatsby-plugin-react-helmet": "^3.0.12",
    "gatsby-plugin-sharp": "^2.0.36",
    "gatsby-source-filesystem": "^2.0.33",
    "gatsby-source-graphql": "^2.0.18",
    "gatsby-source-shopify": "^2.0.28",
    "gatsby-transformer-sharp": "^2.1.19",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-helmet": "^5.2.1"
  },
  "devDependencies": {
    "prettier": "^1.17.0"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write src/**/*.{js,jsx}",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/iamskok/gatsby-shopify-starter"
  },
  "bugs": {
    "url": "https://github.com/iamskok/gatsby-shopify-starter/issues"
  }
}

预期结果是对 Shopify Admin API 进行成功的 GraphQL 查询。实际结果是带有400 状态码的服务器错误。

【问题讨论】:

    标签: javascript graphql shopify gatsby


    【解决方案1】:

    这里有一些问题。

    首先你需要传递X-Shopify-Storefront-Access-Token 而不是X-Shopify-Access-Token。 ( 如果您真的在使用私人应用程序)

    那么你需要请求/api/2019-04/graphql而不是/admin/api/2019-04/graphql.json"。

    请参考此文档:https://help.shopify.com/en/api/custom-storefronts/storefront-api/getting-started#accessing-the-storefront-api-graphql-endpoint

    【讨论】:

    • 也许问题并不清楚,但我可以使用 gatsby-source-Shopify 插件从 Storefront API 查询数据。我在查询 Admin API 时遇到问题,并假设它与 gatsby-source-qraphql 插件配置有关。
    • StorefrontAPI 用于面向公众的应用程序。另一方面,Admin API 是一个不同的野兽,你不能从像 Storefront API 这样的公共应用程序中使用它。
    • @DavidLazar 我没有使用公共应用程序。这是一个私人应用程序,它在问题描述中。
    • 对不起。对我来说 Gatsby 是一个用 React 构建的 JS 博客引擎。即)前端代码。我错过了您使用它构建后端 Shopify 应用程序的部分。对不起。
    【解决方案2】:

    您的gatsby-source-graphql 设置与以下设置中的curl 命令不同:

    • POST HTTP 方法
    • Content-Type: application/graphql标头

    为了匹配 curl 命令,您可以尝试以下设置:

        {
          resolve: "gatsby-source-graphql",
          options: {
            typeName: "ShopifyAdmin",
            fieldName: "admin",
            url: `https://${process.env.SHOP_NAME}.myshopify.com/admin/api/2019-04/orders.json`,
            headers: {
              'X-Shopify-Access-Token': `${process.env.ADMIN_PASSWORD}`,
       +      'Content-Type': 'application/graphql',
            },
       +    fetchOptions: {
       +      method: 'POST'
       +    }
            refetchInterval: 60
          },
        },
    
    

    【讨论】:

    • 这是我在更新 gatsby-config.js 后收到的错误消息:```error Plugin gatsby-source-graphql 返回了一个错误 Error: Parse error on "operationName" (STRING) at [1, 2 ] ```
    • @iamskok 你还看到ServerError: Response not successful: Received status code 400 吗?
    • 是的,它修复了ServerError: Response not successful: Received status code 400,但现在我得到了Parse error on "operationName" (STRING) at [1, 2] 。
    • @iamskok 很好,这就是进步。谁在抛出错误?是gatsby-source-graphql吗?您会编辑 q' 以包含完整的新错误吗?
    • 是的,gatsby-source-graphql。 Error: Parse error on "operationName" (STRING) at [1, 2]
    猜你喜欢
    • 1970-01-01
    • 2021-05-08
    • 2020-03-10
    • 2020-08-11
    • 2021-04-14
    • 2019-04-02
    • 2020-07-23
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多