Node.js 接入随性 API 完整教程

作者:

在

方式一:使用 openai 官方 SDK

npm install openai
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.API_KEY,
  baseURL: "https://api.ns666.cfd/v1",
});

const resp = await client.chat.completions.create({
  model: "deepseek-v4-flash",
  messages: [{ role: "user", content: "你好" }],
});

console.log(resp.choices[0].message.content);

方式二:原生 fetch(零依赖)

const resp = await fetch("https://api.ns666.cfd/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.API_KEY}`,
  },
  body: JSON.stringify({
    model: "deepseek-v4-flash",
    messages: [{ role: "user", content: "你好" }],
  }),
});

const data = await resp.json();
console.log(data.choices[0].message.content);

流式输出(Node 原生)

const resp = await fetch("https://api.ns666.cfd/v1/chat/completions", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
    Authorization: `Bearer ${process.env.API_KEY}`,
  },
  body: JSON.stringify({
    model: "deepseek-v4-flash",
    messages: [{ role: "user", content: "写一段介绍" }],
    stream: true,
  }),
});

const reader = resp.body.getReader();
const decoder = new TextDecoder();

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  for (const line of decoder.decode(value).split("n")) {
    if (!line.startsWith("data: ")) continue;
    const payload = line.slice(6);
    if (payload === "[DONE]") continue;
    try {
      const json = JSON.parse(payload);
      const delta = json.choices && json.choices[0] && json.choices[0].delta.content;
      if (delta) process.stdout.write(delta);
    } catch (e) {}
  }
}

TypeScript 类型提示

interface ChatMessage {
  role: "system" | "user" | "assistant";
  content: string;
}

async function chat(messages: ChatMessage[]): Promise<string> {
  const resp = await fetch("https://api.ns666.cfd/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${process.env.API_KEY}`,
    },
    body: JSON.stringify({ model: "deepseek-v4-flash", messages }),
  });
  const data = await resp.json();
  return data.choices[0].message.content;
}

相关文档