> ## Documentation Index
> Fetch the complete documentation index at: https://docs.aibase.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js 调用

> 使用 Node.js 原生 fetch 调用 AIBase API，并处理超时、HTTP 状态和业务错误。

下面的示例使用 Node.js 原生 `fetch`，无需安装第三方请求库。API Key 从环境变量读取，不会写入源代码。

## 运行要求

* Node.js 18 或更高版本
* 已创建并保存 AIBase API Key

```bash theme={null}
node --version
```

## 设置 API Key

<Tabs>
  <Tab title="PowerShell">
    ```powershell theme={null}
    $env:AIBASE_API_KEY = "AIBase_xxxxxxxxxxxxxxxx"
    ```
  </Tab>

  <Tab title="macOS / Linux">
    ```bash theme={null}
    export AIBASE_API_KEY="AIBase_xxxxxxxxxxxxxxxx"
    ```
  </Tab>
</Tabs>

## 完整示例

将以下内容保存为 `aibase-example.mjs`：

```javascript theme={null}
import { randomUUID } from "node:crypto";

const apiKey = process.env.AIBASE_API_KEY;
if (!apiKey) {
  throw new Error("请先设置 AIBASE_API_KEY 环境变量");
}

const response = await fetch("https://api.aibase.cn/v1/openapi/tasks", {
  method: "POST",
  headers: {
    "AIBase-API-Key": apiKey,
    "AIBase-Request-Id": randomUUID(),
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    apiCode: "geo.questions_corr_recommend",
    data: { keyword: "多智能体系统" },
  }),
  signal: AbortSignal.timeout(30_000),
});

const rawBody = await response.text();
let payload;

try {
  payload = JSON.parse(rawBody);
} catch {
  throw new Error(`AIBase 返回了非 JSON 响应，HTTP ${response.status}`);
}

if (!response.ok) {
  throw new Error(`AIBase HTTP ${response.status}: ${payload.msg ?? "未知错误"}`);
}

if (payload.code !== 200) {
  throw new Error(`AIBase 业务错误 ${payload.code}: ${payload.msg ?? "未知错误"}`);
}

const result = payload.data?.result ?? {};
console.log("requestId:", payload.data?.requestId);
console.log("AI 相关问题:", result.aiQuestions ?? []);
console.log("百度相关问题:", result.baiduQuestions ?? []);
```

```bash theme={null}
node aibase-example.mjs
```

<Note>
  示例中的 30 秒是客户端超时设置示例，不代表平台承诺的响应时限。生产代码还应根据业务需要添加有限重试和日志关联。
</Note>

## 浏览器使用限制

API Key 属于服务端凭证。不要把这段代码直接放入网页前端，也不要通过公开环境变量或打包配置把密钥发送到浏览器。

<Columns cols={2}>
  <Card title="查看字段定义" icon="braces" href="/api-reference/question-discovery">
    核对请求和响应对象的完整结构。
  </Card>

  <Card title="响应处理" icon="triangle-alert" href="/quickstart/response-errors">
    区分 HTTP 错误和业务错误。
  </Card>
</Columns>
