使用 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 密钥保存在服务器端——切勿将其发送到浏览器。
下一步
- 面向 AI 智能体的 Google Search API(LangChain/RAG)
- 使用 n8n / Make / Zapier 实现无代码
- 其他语言:Python · PHP · Go