Strapi 客户端
¥Strapi Client
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
-
Strapi 项目已创建并正在运行。如果你尚未设置,请按照 快速入门指南 创建一个。
¥A Strapi project has been created and is running. If you haven't set one up yet, follow the Quick Start Guide to create one.
-
你知道 Strapi 实例的内容 API 的 URL(例如
http://localhost:1337/api
)。¥You know the URL of the Content API of your Strapi instance (e.g.,
http://localhost:1337/api
).
安装
¥Installation
要在你的项目中使用 Strapi 客户端,请使用你首选的包管理器将其作为依赖安装:
¥To use the Strapi Client in your project, install it as a dependency using your preferred package manager:
- Yarn
- NPM
- pnpm
yarn add @strapi/client
npm install @strapi/client
pnpm add @strapi/client
基本配置
¥Basic configuration
要开始与 Strapi 后端交互,请初始化 Strapi 客户端并设置基本 API URL:
¥To start interacting with your Strapi back end, initialize the Strapi Client and set the base API URL:
- JavaScript
- TypeScript
- Browser (UMD)
使用 Javascript,导入 strapi
函数并创建客户端实例:
¥With Javascript, import the strapi
function and create a client instance:
import { strapi } from '@strapi/client';
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:
import { strapi } from '@strapi/client';
const client = strapi({ baseURL: 'http://localhost:1337/api' });
如果你在浏览器环境中使用 Strapi 客户端,可以使用 <script>
标签将其包含进来。
¥If you're using the Strapi Client in a browser environment, you can include it using a <script>
tag.
<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
Strapi 客户端支持不同的身份验证策略来访问 Strapi 后端中受保护的资源。
¥The Strapi Client supports different authentication strategies to access protected resources in your Strapi back end.
如果你的 Strapi 实例使用 API 令牌,请按如下方式配置 Strapi 客户端:
¥If your Strapi instance uses API tokens, configure the Strapi Client as follows:
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
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 的通用 API 请求的实用方法。 |
collection() | 管理集合类型资源(例如,博客文章、产品)。 |
single() | 管理单一类型资源(例如,主页设置、全局配置)。 |
files() | 支持直接从 Strapi 媒体库上传、检索和管理文件。 |
通用获取
¥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:
const result = await client.fetch('articles', { method: 'GET' });
使用集合类型
¥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?) | 更新现有文档。 |
使用示例:
¥Usage examples:
- JavaScript
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
Strapi 中的单一类型代表仅存在一次的唯一内容条目(例如,主页设置或站点范围的配置)。Strapi 客户端提供了一种 single()
方法来与这些资源交互,可用的方法如下:
¥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:
范围 | 描述 |
---|---|
find(queryParams?) | 获取文档。 |
update(documentID, data, queryParams?) | 更新文档。 |
delete(queryParams?) | 删除文档。 |
使用示例:
¥Usage examples:
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
Strapi 客户端通过 files
属性提供对 媒体库 的访问。这允许你检索和管理文件元数据,而无需直接与 REST API 交互。
¥The Strapi Client provides access to the 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?) | 根据可选查询参数检索文件元数据列表 |
findOne(fileId) | 通过 ID 检索单个文件的元数据 |
update(fileId, fileInfo) | 更新现有文件的元数据 |
upload(file, options) | 上传文件(Blob 或 Buffer),并附带一个可选的 options 对象作为元数据。 |
delete(fileId) | 通过 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:
// 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
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:
// 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:
// 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
NewThis content is new.
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
async upload(file: Blob, options?: BlobUploadOptions): Promise<MediaUploadResponse>
async upload(file: Buffer, options: BufferUploadOptions): Promise<MediaUploadResponse>
-
对于
Blob
上传,options
是可选的,并且可以包含fileInfo
作为元数据。¥For
Blob
uploads,options
is optional and may includefileInfo
for metadata. -
对于
Buffer
上传,options
必须包含filename
和mimetype
,并且可以包含fileInfo
。¥For
Buffer
uploads,options
must includefilename
andmimetype
, and may includefileInfo
.
响应是一个文件对象数组,每个对象包含诸如 id
、name
、url
、size
和 mime
source 之类的详细信息。
¥The response is an array of file objects, each containing details such as id
, name
, url
, size
, and mime
source.
- Upload a file with the browser
- Upload a file with Node.js
你可以通过浏览器上传文件,如下所示:
¥You can upload a file use through the browser as follows:
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:
- Uploading a Blob
- Uploading a Buffer
import { readFile } from 'fs/promises';
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);
}
import { readFile } from 'fs/promises';
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
strapi.client.files.upload()
方法返回一个文件对象数组,每个对象包含如下字段:
¥The strapi.client.files.upload()
method returns an array of file objects, each with fields such as:
{
"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"
}
上传响应包含除上述字段之外的其他字段。有关所有可用字段,请参阅 客户端源代码 中的完整 FileResponse 接口。
¥The upload response includes additional fields beyond those shown above. See the complete FileResponse interface in the client source code for all available fields.
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:
// 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);
常见错误处理
¥Handling Common Errors
通过 Strapi 客户端发送查询时可能会出现以下错误:
¥The following errors might occur when sending queries through the Strapi Client:
错误 | 描述 |
---|---|
权限错误 | 如果经过身份验证的用户没有上传或管理文件的权限,则会抛出 FileForbiddenError 错误。 |
HTTP 错误 | 如果服务器无法访问、身份验证失败或出现网络问题,则会抛出 HTTPError 错误。 |
缺少参数 | 上传 Buffer 时,必须在选项对象中同时提供 filename 和 mimetype 属性。如果缺少其中任何一个,则会引发错误。 |
有关 Strapi 客户端的更多详细信息,请参阅 软件包的 README。
¥More details about the Strapi Client may be found in the package's README.