使用graphql-js-schema-fetch获取Shopify GraphQL Schema报错求助
解决graphql-js-schema-fetch获取Shopify GraphQL Schema时的解析错误
我之前用这个工具爬取Shopify Schema时也踩过类似的坑,你遇到的这个解析错误本质是请求格式不匹配导致的,给你几个具体的排查和解决方向:
1. 修正Content-Type请求头
你当前设置的Content-Type: application/graphql是核心问题之一。Shopify Storefront API虽支持该类型,但graphql-js-schema-fetch工具默认会把查询内容包装成{"query": "..."}的JSON格式,这就导致当你指定application/graphql时,Shopify服务器会把整个JSON字符串当成纯查询语句解析,自然会在第1行第2位碰到"query"这个不符合GraphQL语法的字符串,抛出解析错误。
把Content-Type改成application/json就能解决格式冲突:
graphql-js-schema-fetch https://myspati-com.myshopify.com/api/graphql --header "Content-Type: application/json" --header "X-Shopify-Storefront-Access-Token: <access-token>"
2. 手动指定标准Introspection Query
如果修改请求头后还是不行,可能是工具默认的查询语句有问题。你可以手动创建一个标准的GraphQL自省查询文件,强制工具使用这个查询:
- 创建
introspection.graphql文件,写入以下内容:
query IntrospectionQuery { __schema { queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } directives { name description locations args { ...InputValue } } } } fragment FullType on __Type { kind name description fields(includeDeprecated: true) { name description args { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name } } } }
- 执行命令时指定这个查询文件:
graphql-js-schema-fetch https://myspati-com.myshopify.com/api/graphql --header "Content-Type: application/graphql" --header "X-Shopify-Storefront-Access-Token: <access-token>" --query ./introspection.graphql
3. 验证Storefront Access Token的有效性
最后别忘了检查你的访问令牌:
- 确认这个令牌是Storefront API令牌,不是Admin API的令牌(两者权限范围完全不同)
- 检查Shopify后台是否已经启用了Storefront API,并且令牌拥有
read_product_listings等必要的读取权限
按照上面的步骤调整后,应该就能成功获取到Shopify的GraphQL Schema了。
内容的提问来源于stack exchange,提问作者magic.77
相关产品推荐
相关产品推荐

