← 返回博客

Node.js 中的 Google Search API:完整教程(2026)

在 Node.js / JavaScript 中使用 Google Search API——基于 fetch 的请求、异步分页、重试以及类型化辅助函数。使用 serp.cheap 的可复制粘贴示例。

1 分钟阅读

使用 serp.cheap,从 Node.js 查询 Google 并获取结构化 JSON。Node 18+ 内置了 fetch——无需任何依赖。

最小示例

const res = await fetch("https://api.serp.cheap/v1/search", {
  method: "POST",
  headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({ q: "best electric cars 2026", gl: "us", page: 1 }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { organic, stats } = await res.json();
organic.forEach(r => console.log(`#${r.position} ${r.title} — ${r.link}`));
console.log("cost (credits):", stats.cost, "cached:", stats.cached);

一个带重试的小辅助函数

async function search(q, { gl = "us", page = 1, tbs, retries = 4 } = {}) {
  const body = JSON.stringify({ q, gl, page, ...(tbs && { tbs }) });
  for (let attempt = 0; ; attempt++) {
    const res = await fetch("https://api.serp.cheap/v1/search", {
      method: "POST",
      headers: { "X-API-Key": process.env.SERP_KEY, "Content-Type": "application/json" },
      body,
    });
    if (res.ok) return res.json();
    if (![429, 500, 502, 503, 504].includes(res.status) || attempt >= retries) {
      throw new Error(`HTTP ${res.status}`);
    }
    await new Promise(r => setTimeout(r, 1000 * 2 ** attempt)); // backoff
  }
}

const data = await search("serp api nodejs", { gl: "us" });

分页

async function pages(q, n = 3) {
  const results = [];
  for (let p = 1; p <= n; p++) results.push(...(await search(q, { page: p })).organic);
  return results;
}

每一页都是单独计费的请求。请将你的 API 密钥保存在服务器端——切勿将其发送到浏览器。

下一步

Frequently asked questions

如何在 Node.js 中调用 Google Search API?+

使用内置的 fetch(Node 18+)发起 POST 请求来提交查询。使用 serp.cheap:fetch('https://api.serp.cheap/v1/search', { method: 'POST', headers: { 'X-API-Key': KEY, 'Content-Type': 'application/json' }, body: JSON.stringify({ q, gl: 'us' }) })。

我需要 SDK 吗?+

不一定需要——SERP API 就是一个普通的 HTTP 端点,所以原生 fetch(或 axios)就足够了。不过 serp.cheap 也提供官方的 JavaScript/TypeScript SDK(npm install @serpcheap/sdk),带有类型化调用、重试和分页,外加 NestJS 和 Next.js 集成。

获取你的 API 密钥

直接购买最便宜, 用银行卡或加密货币支付,无需 KYC。或通过市场。