CokeAPI
SDK 与集成

浏览器 / JavaScript

在浏览器里直接调 CokeAPI 的注意事项与替代方案。

强烈不推荐在浏览器前端直接调 CokeAPI。任何前端代码 (含混淆 / Webpack chunk) 里的 API Key 都会被用户嗅探到,导致 Key 泄漏 → 被恶意刷量 → 余额耗尽。

生产应用应当走自家后端代理:浏览器 → 自家 API → CokeAPI。

推荐架构

┌─────────┐         ┌──────────┐         ┌──────────────┐
│ 浏览器  │ ───────►│ 自家后端 │ ───────►│ CokeAPI /v1  │
│ (无 Key)│  fetch  │ (持 Key) │ Bearer  │              │
└─────────┘         └──────────┘         └──────────────┘

自家后端做的事:

  1. 鉴权:验证浏览器侧用户是否登录
  2. 限流:对单用户做应用层限流 (避免单个用户刷光你的 Key 配额)
  3. 转发:把请求 + Bearer 头发到 https://api.cokeapi.com/v1/...
  4. 审计:记录每个用户的调用,便于追溯

仅用于调试 / 内部工具

如果是只你自己用的 console / 浏览器调试,可以这样:

// 仅本地调试,不要部署
const KEY = "sk-coke-xxxxxxxx";

const r = await fetch("https://api.cokeapi.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "gpt-4o-mini",
    messages: [{ role: "user", content: "hi" }],
  }),
});
console.log(await r.json());

CORS:CokeAPI 服务端默认允许 https://*.cokeapi.comhttp://localhost:* 跨域,其他来源需联系商务加白名单。

流式 (SSE) 在浏览器

fetch 原生 ReadableStream + TextDecoderStream:

const resp = await fetch("https://api.cokeapi.com/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "grok-4.20-fast",
    messages: [{ role: "user", content: "讲个笑话" }],
    stream: true,
  }),
});

const reader = resp.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = "";
while (true) {
  const { value, done } = await reader.read();
  if (done) break;
  buffer += value;
  const lines = buffer.split("\n");
  buffer = lines.pop()!;
  for (const line of lines) {
    if (!line.startsWith("data: ")) continue;
    const data = line.slice(6);
    if (data === "[DONE]") return;
    const json = JSON.parse(data);
    process.stdout.write(json.choices[0]?.delta?.content ?? "");
  }
}

Vercel AI SDK / Next.js Route Handler

更推荐用 Vercel AI SDK,前端组件直接 useChat(),后端 Route Handler 里持 Key,自动处理流式。

On this page