> For the complete documentation index, see [llms.txt](https://docs.apismart.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.apismart.ai/documentation/zh-tw/sdk-yu-qian-yi/javascript-yu-typescript.md).

# JavaScript 與 TypeScript

使用 JavaScript 或 TypeScript 搭配內建的 `fetch` API。

本指南示範 Chat Completions、圖片生成和影片生成的基本設定。

關於一般 API 規則，請參閱 [**API 基礎**](/documentation/zh-tw/api-zhi-nan/api-ji-chu.md).

***

### 開始之前

請確認你具備：

* Node.js 18 或更新版本
* 一個已啟用的 **API 權杖**
* 充足的 **目前餘額**
* 一個有效的 **模型 ID**

將您的 API Token 設為環境變數：

```bash
export APISMART_API_KEY="YOUR_API_KEY"
```

在 PowerShell 中：

```powershell
$env:APISMART_API_KEY="YOUR_API_KEY"
```

> 🔐 請將你的 API Token 保存在安全的伺服器端環境中。不要將它暴露在瀏覽器端程式碼中。

***

### 基本設定

```javascript
const apiKey = process.env.APISMART_API_KEY;

if (!apiKey) {
  throw new Error("APISMART_API_KEY is not set.");
}

const headers = {
  Authorization: `Bearer ${apiKey}`,
  "Content-Type": "application/json",
};
```

相同的驗證標頭可重複用於受支援的 ApiSmart 端點。

***

### 聊天完成

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/chat/completions",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      messages: [
        {
          role: "user",
          content: "Hello!",
        },
      ],
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

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

替換 `YOUR_MODEL_ID` 使用所選模型中顯示的確切值 **程式碼範例**.

***

### 圖片生成

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/images/generations",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      prompt: "日落時分的未來城市",
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

console.log(result);
```

圖片請求與回應欄位可能因模型而異。

***

### 影片生成

影片生成使用非同步任務工作流程。

對於接受以下內容的影片模型 `prompt` 與 `duration`:

```javascript
const response = await fetch(
  "https://gw.apismart.ai/v1/video/tasks",
  {
    method: "POST",
    headers,
    body: JSON.stringify({
      model: "YOUR_MODEL_ID",
      prompt: "日落時分的電影感海浪景象",
      duration: 5,
    }),
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();
const taskId = result.id;

console.log(taskId);
```

檢查任務狀態：

```javascript
const response = await fetch(
  `https://gw.apismart.ai/v1/video/tasks/${taskId}`，
  {
    headers: {
      Authorization: `Bearer ${apiKey}`,
    },
  }
);

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const result = await response.json();

console.log(result);
```

> ⚠️ **重要：** 影片模型可能會使用不同的欄位，例如 `prompt`, `content`, `size`，或 `resolution`. 請一律遵循所選模型的 **程式碼範例**.

***

### TypeScript

相同的請求結構也適用於 TypeScript。

例如：

```typescript
interface ChatResponse {
  choices: Array<{
    message: {
      role: string;
      content: string;
    };
  }>;
}

const result = (await response.json()) as ChatResponse;

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

當回應結構不同時，請使用特定模型的型別。

***

### 🛠️ 常見問題

| 問題        | 檢查項目                  |
| --------- | --------------------- |
| **驗證失敗**  | API Token 與 Bearer 標頭 |
| **找不到模型** | 精確的模型 ID 與大小寫         |
| **無效的請求** | 端點、JSON 主體與模型特定欄位     |
| **請求失敗**  | HTTP 狀態與回傳的錯誤訊息       |
| **餘額不足**  | 目前餘額與 API 權杖剩餘額度      |

排除問題時，請檢查 [**使用紀錄與成本**](/documentation/zh-tw/api-shi-yong/shi-yong-ji-lu-yu-fei-yong.md).

> 🔐 絕不要在前端程式碼、日誌、螢幕截圖或支援訊息中包含你的完整 API Token。

***

### 🚀 下一步

繼續進行：

* [**Python**](/documentation/zh-tw/sdk-yu-qian-yi/python.md)
* [**cURL**](/documentation/zh-tw/sdk-yu-qian-yi/curl.md)
* [**API 基礎**](/documentation/zh-tw/api-zhi-nan/api-ji-chu.md)
* [**Chat Completions API**](/documentation/zh-tw/api-zhi-nan/liao-tian-wan-cheng-api.md)
* [**圖片生成 API**](/documentation/zh-tw/api-zhi-nan/tu-pian-sheng-cheng-api.md)
* [**影片生成 API**](/documentation/zh-tw/api-zhi-nan/ying-pian-sheng-cheng-api.md)
