You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify产品GID数组GraphQL查询报错,如何解决并实现发布日期排序?

问题原因及修正方案

核心错误

你在GraphQL查询的变量定义部分,直接把具体的产品ID数组写在了类型声明的位置,这不符合GraphQL语法规范。GraphQL要求变量定义只声明类型,变量的实际取值要单独放在variables对象中传递。

修正步骤及代码

  1. 修正查询字符串:变量定义只保留类型(产品ID属于ID类型,数组用[ID!]!表示非空的ID数组),移除硬编码的ID值。
  2. 分离变量值:把产品ID数组放在variables字段中,和query平级。
  3. 添加排序逻辑:如果要按发布日期从新到旧排序,nodes查询不支持排序,改用products查询,通过sortKey: CREATED_AT和reverse: true实现排序需求。

修正后的完整代码:

const token = 'Storefront API custom app token';

// 修正后的查询:变量只声明类型,添加排序参数
const query = `query ($ids: [ID!]!) {
  products(ids: $ids, sortKey: CREATED_AT, reverse: true) {
    edges {
      node {
        id
        title
        createdAt # 可以加上发布日期字段验证排序结果
      }
    }
  }
}`;

// 把查询和变量分开,一起序列化为JSON
const queryPage = JSON.stringify({
  query: query,
  variables: {
    ids: ["gid://shopify/Product/777229615129", "gid://shopify/Product/7772297068794"]
  }
});

const storefrontSettingsPage = {
  async: true,
  crossDomain: true,
  url: `https://${shopname}.myshopify.com/api/2022-07/graphql.json`,
  method: "POST",
  headers: {
    "X-Shopify-Storefront-Access-Token": token,
    "Content-Type": "application/json"
  },
  data: queryPage,
};

$.ajax(storefrontSettingsPage).done(function (response) {
  console.log(response);
});

额外说明

  • 原代码中用nodes查询虽然能获取指定ID的产品,但不支持排序参数,所以改用products查询来满足排序需求。
  • sortKey: CREATED_AT指定按创建时间排序,reverse: true实现倒序(从新到旧)。
  • 变量传递是GraphQL的标准用法,这样不仅避免语法错误,还能让查询更灵活,方便后续动态修改ID列表。

内容的提问来源于stack exchange,提问作者Garcia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:01:17