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

Shopify REST API分页问题:获取全量产品及提取page_info

提取Shopify API响应头中rel="next"的page_info参数

在Node.js中处理Shopify REST API的分页响应头,有两种可靠的方法提取rel="next"对应的page_info参数:

方法一:正则表达式匹配(简洁高效)

直接用正则匹配出rel="next"对应的URL,再从中解析page_info参数:

// 假设response是你发起API请求后得到的响应对象
const linkHeader = response.headers.link;

if (!linkHeader) {
  // 无下一页,终止分页逻辑
  return;
}

// 匹配rel="next"的链接片段
const nextLinkRegex = /<([^>]+)>;\s*rel="next"/;
const matchResult = linkHeader.match(nextLinkRegex);

if (matchResult) {
  const nextUrl = matchResult[1];
  // 解析URL中的查询参数
  const searchParams = new URLSearchParams(new URL(nextUrl).search);
  const nextPageInfo = searchParams.get('page_info');
  // nextPageInfo就是下一页需要的参数
  console.log(nextPageInfo);
} else {
  console.log('已获取全部产品,无下一页');
}

方法二:手动拆分解析(直观易理解)

如果对正则不熟悉,可以通过字符串拆分逐步提取:

const linkHeader = response.headers.link;

if (!linkHeader) return;

// 分割每个分页链接条目
const linkItems = linkHeader.split(',').map(item => item.trim());

for (const item of linkItems) {
  // 拆分URL部分和rel属性部分
  const [urlSegment, relSegment] = item.split(';').map(segment => segment.trim());
  // 去掉URL的尖括号
  const targetUrl = urlSegment.slice(1, -1);
  // 提取rel属性的值
  const relMatch = relSegment.match(/rel="([^"]+)"/);
  
  if (relMatch && relMatch[1] === 'next') {
    const searchParams = new URLSearchParams(new URL(targetUrl).search);
    const nextPageInfo = searchParams.get('page_info');
    console.log(nextPageInfo);
    break; // 找到next后即可终止循环
  }
}

注意事项

Shopify REST API的分页逻辑中,page_info分页比last_id更可靠,能避免因产品删除、排序变更导致的数据遗漏问题,建议始终使用Link头的分页方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 16:20:45