# Strapi 客户端

> Source: https://strapi.nodejs.cn/cms/api/client

🌐 Strapi Client

Strapi 客户端是一个 JavaScript 库，它简化了与 Strapi 后端的交互，用于通过 `collection()`、`single()` 和 `files()` 方法获取、创建、更新和删除内容。

🌐 The Strapi Client is a JavaScript library that simplifies interactions with your Strapi back end for fetching, creating, updating, and deleting content through `collection()`, `single()`, and `files()` methods.

Strapi 客户端库简化了与 Strapi 后端的交互，提供了一种获取、创建、更新和删除内容的方式。本指南将引导你完成 Strapi 客户端的设置、身份验证配置，以及有效使用其主要功能。

🌐 The Strapi Client library simplifies interactions with your Strapi back end, providing a way to fetch, create, update, and delete content. This guide walks you through setting up the Strapi Client, configuring authentication, and using its key features effectively.

## 入门 {#getting-started}

🌐 Getting Started

:::prerequisites

- Strapi 项目已创建并正在运行。如果你还没有设置，请按照[快速入门指南](/cms/quick-start)创建一个。
- 你知道你的 Strapi 实例的内容 API 的 URL（例如，`http://localhost:1337/api`）。

:::

### 安装 {#installation}

🌐 Installation

要在你的项目中使用 Strapi 客户端，请使用你首选的包管理器将其作为依赖安装：

🌐 To use the Strapi Client in your project, install it as a dependency using your preferred package manager:

  ```bash
  yarn add @strapi/client
  ```
  ```bash
  npm install @strapi/client
  ```
  ```bash
    pnpm add @strapi/client
  ```

### 基本配置 {#basic-configuration}

🌐 Basic configuration

要开始与 Strapi 后端交互，请初始化 Strapi 客户端并设置基本 API URL：

🌐 To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:

<Tabs groupId="js-ts"> 
使用 Javascript，导入 `strapi` 函数并创建一个客户端实例：

🌐 With Javascript, import the `strapi` function and create a client instance:

```js

const client = strapi({ baseURL: 'http://localhost:1337/api' });
```

使用 Typescript，导入 `strapi` 函数，并使用你的 Strapi API 基础 URL 创建一个客户端实例：

🌐 With Typescript, import the `strapi` function and create a client instance with your Strapi API base URL:

```typescript

const client = strapi({ baseURL: 'http://localhost:1337/api' });
```

<TabItem value="browser" label="Browser (UMD)">
如果你在浏览器环境中使用 Strapi 客户端，可以使用 `<script>` 标签将其包含。 

```js title="./src/api/[apiName]/routes/[routerName].ts (e.g './src/api/restaurant/routes/restaurant.ts')"
<script src="https://cdn.jsdelivr.net/npm/@strapi/client"></script>

<script>
  const client = strapi.strapi({ baseURL: 'http://localhost:1337/api' });
</script>
```

`baseURL` 必须包含协议（`http` 或 `https`）。无效的 URL 将抛出错误 `StrapiInitializationError`。

🌐 The `baseURL` must include the protocol (`http` or `https`). An invalid URL will throw an error `StrapiInitializationError`.

### 身份验证 {#authentication}

🌐 Authentication

Strapi 客户端支持不同的身份验证策略来访问 Strapi 后端中受保护的资源。

🌐 The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.

如果你的 Strapi 实例使用 [API 令牌](/cms/features/api-tokens)，请按如下方式配置 Strapi 客户端：

🌐 If your Strapi instance uses [API tokens](/cms/features/api-tokens), configure the Strapi Client as follows:

```js
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token-here',
});
```

这允许你的请求自动包含必要的身份验证凭据。如果令牌无效或缺失，客户端在初始化时将抛出错误 `StrapiValidationError`。

🌐 This allows your requests to include the necessary authentication credentials automatically.
If the token is invalid or missing, the client will throw an error during initialization `StrapiValidationError`.

## API参考 {#api-reference}

🌐 API Reference

Strapi 客户端提供以下关键属性和方法用于与你的 Strapi 后端交互：

🌐 The Strapi Client provides the following key properties and methods for interacting with your Strapi back end:

| 参数 | 描述 |
| ---| --- |
| `baseURL` | 你的 Strapi 后端的基础 API URL。 |
| `fetch()` | 一个用于发起通用 API 请求的工具方法，类似于原生 fetch API。 |
| `collection()` | 管理集合类型资源（例如博客文章、产品）。 |
| `single()` | 管理单一类型资源（例如主页设置、全局配置）。 |
| `files()` | 直接向 Strapi 媒体库上传、检索和管理文件的功能。 |

### 通用抓取 {#general-purpose-fetch}

🌐 General purpose fetch

Strapi 客户端提供了对底层 JavaScript `fetch` 函数的访问，以便直接进行 API 请求。请求总是相对于客户端初始化时提供的基础 URL:

🌐 The Strapi Client provides access to the underlying JavaScript `fetch` function to make direct API requests. The request is always relative to the base URL provided during client initialization:

```js
const result = await client.fetch('articles', { method: 'GET' });
```

### 与集合类型一起工作 {#working-with-collection-types}

🌐 Working with collection types

Strapi 中的集合类型是具有多个条目的实体（例如，拥有多篇文章的博客）。Strapi 客户端提供了一个 `collection()` 方法来与这些资源进行交互，具有以下可用方法：

🌐 Collection types in Strapi are entities with multiple entries (e.g., a blog with many posts). The Strapi Client provides a `collection()` method to interact with these resources, with the following methods available:

| 参数 | 描述 |
| ---| --- |
| `find(queryParams?)` | 获取多个文档，可选择性地进行过滤、排序或分页。 |
| `findOne(documentID, queryParams?)` | 根据唯一 ID 检索单个文档。 |
| `create(data, queryParams?)` | 在集合中创建新文档。 |
| `update(documentID, data, queryParams?)` | 更新现有文档。 |
| `delete(documentID, queryParams?)` | 删除现有文档。 |

**使用示例：**
```js
const articles = client.collection('articles');

// Fetch all english articles sorted by title
const allArticles = await articles.find({
  locale: 'en',
  sort: 'title',
});

// Fetch a single article
const singleArticle = await articles.findOne('article-document-id');

// Create a new article
const newArticle = await articles.create({ title: 'New Article', content: '...' });

// Update an existing article
const updatedArticle = await articles.update('article-document-id', { title: 'Updated Title' });

// Delete an article
await articles.delete('article-id');
```

### 处理单一类型 {#working-with-single-types}

🌐 Working with single types

Strapi 中的单一类型表示只存在一次的独特内容条目（例如首页设置或全站配置）。Strapi 客户端提供了 `single()` 方法来与这些资源进行交互，可用的方法如下：
| 参数 | 描述 |
| ----------| -------------------------------------------------------------------------------------------- |
| `find(queryParams?)`  | 获取文档。 |
| `update(documentID, data, queryParams?)`  | 更新文档。 |
| `delete(queryParams?)`  | 删除文档。 |

🌐 Single types in Strapi represent unique content entries that exist only once (e.g., the homepage settings or site-wide configurations). The Strapi Client provides a `single()` method to interact with these resources, with the following methods available:
| Parameter | Description                                                                                  |
| ----------| -------------------------------------------------------------------------------------------- |
| `find(queryParams?)`  | Fetch the document.        |
| `update(documentID, data, queryParams?)`  | Update the document. |
| `delete(queryParams?)`  | Remove the document. |

**使用示例：**

```js
const homepage = client.single('homepage');

// Fetch the default homepage content
const defaultHomepage = await homepage.find();

// Fetch the Spanish version of the homepage
const spanishHomepage = await homepage.find({ locale: 'es' });

// Update the homepage draft content
const updatedHomepage = await homepage.update(
  { title: 'Updated Homepage Title' },
  { status: 'draft' }
);

// Delete the homepage content
await homepage.delete();
```

### 处理文件 {#working-with-files}

🌐 Working with files

Strapi 客户端通过 `files` 属性提供对 [媒体库](/cms/features/media-library) 的访问。这使你能够在不直接与 REST API 交互的情况下检索和管理文件元数据。

🌐 The Strapi Client provides access to the [Media Library](/cms/features/media-library) via the `files` property. This allows you to retrieve and manage file metadata without directly interacting with the REST API.

以下方法可用于处理文件。点击表格中的方法名称即可跳转到相应部分，查看更多详细信息和示例：

🌐 The following methods are available for working with files. Click on the method name in the  table to jump to the corresponding section with more details and examples:

| 方法 | 描述 |
|--------|-------------|
| [`find(params?)`](#find) | 根据可选查询参数检索文件元数据列表 |
| [`findOne(fileId)`](#findone) | 根据文件 ID 检索单个文件的元数据 |
| [`update(fileId, fileInfo)`](#update) | 更新现有文件的元数据 |
| [`upload(file, options)`](#upload) | 上传文件（Blob 或 Buffer），可选提供用于元数据的 `options` 对象 |
| [`delete(fileId)`](#delete) | 根据文件 ID 删除文件 |

#### `find`

`strapi.client.files.find()` 方法根据可选查询参数检索文件元数据列表。

🌐 The `strapi.client.files.find()` method retrieves a list of file metadata based on optional query parameters.

该方法的使用方式如下：

🌐 The method can be used as follows:

```js
// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Find all file metadata
const allFiles = await client.files.find();
console.log(allFiles);

// Find file metadata with filtering and sorting
const imageFiles = await client.files.find({
  filters: {
    mime: { $contains: 'image' }, // Only get image files
    name: { $contains: 'avatar' }, // Only get files with 'avatar' in the name
  },
  sort: ['name:asc'], // Sort by name in ascending order
});
```

#### `findOne` {#findone}

`strapi.client.files.findOne()` 方法通过其 ID 检索单个文件的元数据。

🌐 The `strapi.client.files.findOne()` method retrieves the metadata for a single file by its id.

该方法的使用方式如下：

🌐 The method can be used as follows:

```js
// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Find file metadata by ID
const file = await client.files.findOne(1);
console.log(file.name);
console.log(file.url); 
console.log(file.mime); // The file MIME type
```

#### `update`

`strapi.client.files.update()` 方法更新现有文件的元数据，接受两个参数，`fileId`，以及包含选项的对象，例如媒体的名称、替代文本和标题。

🌐 The `strapi.client.files.update()` method updates metadata for an existing file, accepting 2 parameters, the `fileId`, and an object containing options such as the name, alternative text, and caption for the media.

这些方法的使用方式如下：

🌐 The methods can be used as follows:

```js
// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Update file metadata
const updatedFile = await client.files.update(1, {
  name: 'New file name',
  alternativeText: 'Descriptive alt text for accessibility',
  caption: 'A caption for the file',
});
```

#### `upload`  {#上传}

🌐 `upload`  

Strapi 客户端通过 `FilesManager` 提供媒体文件上传功能，可通过 `strapi.client.files.upload()` 方法访问。该方法允许你将媒体文件（如图片、视频或文档）上传到你的 Strapi 后端。

🌐 The Strapi Client provides media file upload functionality through the `FilesManager`, accessible through the  `strapi.client.files.upload()` method. The method allows you to upload media files (such as images, videos, or documents) to your Strapi backend.

该方法支持将文件作为 `Blob`（在浏览器或 Node.js 中）或作为 `Buffer`（仅在 Node.js 中）上传。该方法还支持向上传的文件附加元数据，例如 `alternativeText` 和 `caption`。

🌐 The method supports uploading files as `Blob` (in browsers or Node.js) or as `Buffer` (in Node.js only). The method also supports attaching metadata to the uploaded file, such as `alternativeText` and `caption`.

##### 方法签名 {#method-signature}

🌐 Method Signature

```js
async upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
async upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadResponse>
```

- 对于 `Blob` 上传，`options` 是可选的，并且可以包含 `fileInfo` 作为元数据。
- 对于 `Buffer` 上传，`options` 必须包含 `filename` 和 `mimetype`，并且可以包含 `fileInfo`。

响应是一个文件对象数组，每个对象包含 `id`、`name`、`url`、`size` 和 `mime` 等详细信息 [source](https://github.com/strapi/client/blob/60a0117e361346073bed1959d354c7facfb963b3/src/files/types.ts)。

🌐 The response is an array of file objects, each containing details such as `id`, `name`, `url`, `size`, and `mime` [source](https://github.com/strapi/client/blob/60a0117e361346073bed1959d354c7facfb963b3/src/files/types.ts).

你可以通过浏览器上传文件，如下所示：

🌐 You can upload a file use through the browser as follows:

```js
const client = strapi({ baseURL: 'http://localhost:1337/api' });

const fileInput = document.querySelector('input[type="file"]');
const file = fileInput.files[0];

try {
  const result = await client.files.upload(file, {
    fileInfo: {
      alternativeText: 'A user uploaded image',
      caption: 'Uploaded via browser',
    },
  });
  console.log('Upload successful:', result);
} catch (error) {
  console.error('Upload failed:', error);
}
```

使用 Node.js，你可以上传 blob 或缓冲区，如下例所示：

🌐 With Node.js, you can either upload a blob or a buffer, as in the following examples:

```js

const client = strapi({ baseURL: 'http://localhost:1337/api' });

const filePath = './image.png';
const mimeType = 'image/png';
const fileContentBuffer = await readFile(filePath);
const fileBlob = new Blob([fileContentBuffer], { type: mimeType });

try {
  const result = await client.files.upload(fileBlob, {
    fileInfo: {
      name: 'Image uploaded as Blob',
      alternativeText: 'Uploaded from Node.js Blob',
      caption: 'Example upload',
    },
  });
  console.log('Blob upload successful:', result);
} catch (error) {
  console.error('Blob upload failed:', error);
}
```

```js

const client = strapi({ baseURL: 'http://localhost:1337/api' });

const filePath = './image.png';
const fileContentBuffer = await readFile(filePath);

try {
  const result = await client.files.upload(fileContentBuffer, {
    filename: 'image.png',
    mimetype: 'image/png',
    fileInfo: {
      name: 'Image uploaded as Buffer',
      alternativeText: 'Uploaded from Node.js Buffer',
      caption: 'Example upload',
    },
  });
  console.log('Buffer upload successful:', result);
} catch (error) {
  console.error('Buffer upload failed:', error);
}
```

##### 响应结构 {#response-structure}

🌐 Response Structure

`strapi.client.files.upload()` 方法返回一个文件对象数组，每个对象都有如下字段：

🌐 The `strapi.client.files.upload()` method returns an array of file objects, each with fields such as:

```json
{
  "id": 1,
  "name": "image.png",
  "alternativeText": "Uploaded from Node.js Buffer",
  "caption": "Example upload",
  "mime": "image/png",
  "url": "/uploads/image.png",
  "size": 12345,
  "createdAt": "2025-07-23T12:34:56.789Z",
  "updatedAt": "2025-07-23T12:34:56.789Z"
}
```

:::note Additional response fields

上传响应包括上述显示内容之外的其他字段。有关所有可用字段，请参阅 [client source code](https://github.com/strapi/client/blob/main/src/files/types.ts) 中的完整 FileResponse 接口。

:::

#### `delete`

`strapi.client.files.delete()` 方法通过其 ID 删除文件。

🌐 The `strapi.client.files.delete()` method deletes a file by its ID.

该方法的使用方式如下：

🌐 The method can be used as follows:

```js
// Initialize the client
const client = strapi({
  baseURL: 'http://localhost:1337/api',
  auth: 'your-api-token',
});

// Delete a file by ID
const deletedFile = await client.files.delete(1);
console.log('File deleted successfully');
console.log('Deleted file ID:', deletedFile.id);
console.log('Deleted file name:', deletedFile.name);
```

<br/>

## 处理常见错误 {#handling-common-errors}

🌐 Handling Common Errors

通过 Strapi 客户端发送查询时可能会出现以下错误：

🌐 The following errors might occur when sending queries through the Strapi Client:

| 错误 | 描述 |
|-------|-------------|
| 权限错误 | 如果经过身份验证的用户没有上传或管理文件的权限，将抛出 `FileForbiddenError`。 |
| HTTP 错误 | 如果服务器无法访问、身份验证失败或存在网络问题，将抛出 `HTTPError`。 |
| 缺少参数 | 当上传 `Buffer` 时，必须在选项对象中提供 `filename` 和 `mimetype`。如果缺少任何一个，将抛出错误。 |

:::strapi Additional information

有关 Strapi 客户端的更多详细信息可以在 [package](https://github.com/strapi/client/blob/main/README.md)中找到。

:::
