管理面板 API:获取客户端
🌐 Admin Panel API: Fetch client
Page summary:在 React 组件内使用
useFetchClient,在其他地方使用getFetchClient来调用附带用户身份验证令牌的 Strapi API。两者都提供get、post、put和del方法,并在收到 401 响应时自动刷新令牌。🌐 Use
useFetchClientinside React components andgetFetchClientelsewhere to call Strapi APIs with the user's authentication token attached. Both exposeget,post,put, anddelmethods with automatic token refresh on 401 responses.
Strapi 为管理面板提供了一个内置的 HTTP 客户端,可以自动管理身份验证。插件开发者应使用它,而不是直接使用 fetch 或 axios。
🌐 Strapi provides a built-in HTTP client for the admin panel that manages authentication automatically. Plugin developers should use it instead of raw fetch or axios.
useFetchClient 和 getFetchClient 都从 @strapi/strapi/admin 导出,并提供相同的 get、post、put 和 del 方法。根据调用的位置进行选择:
🌐 Both useFetchClient and getFetchClient are exported from @strapi/strapi/admin and expose the same get, post, put, and del methods. Choose based on where the call is made from:
| 入口点 | 使用场景 |
|---|---|
useFetchClient | 在 React 组件内部使用(组件卸载时自动取消请求) |
getFetchClient | 服务、工具函数、事件处理程序或任何非 React 代码 |
在深入了解本页的概念之前,请确保你已经:
🌐 Before diving deeper into the concepts on this page, please ensure you have:
- 创建了一个 Strapi 插件,
- 已阅读并理解了 管理面板 API 的基础知识
正在获取数据
🌐 Fetching data
最常见的操作是使用 get 获取数据。导入客户端,解构所需的方法,并 await 结果:
🌐 The most common operation is fetching data with get. Import the client, destructure the methods you need, and await the result:
在 React 组件内部
🌐 Inside a React component
useFetchClient 是一个 React 钩子,它会自动提供一个与组件生命周期绑定的 AbortSignal,因此在组件卸载时请求会被取消:
- JavaScript
- TypeScript
import { useFetchClient } from '@strapi/strapi/admin';
const MyComponent = () => {
const { get } = useFetchClient();
const fetchData = async () => {
const { data } = await get('/my-plugin/my-endpoint');
// data contains the parsed JSON response
};
};
import { useFetchClient } from '@strapi/strapi/admin';
const MyComponent = () => {
const { get } = useFetchClient();
const fetchData = async () => {
const { data } = await get('/my-plugin/my-endpoint');
// data contains the parsed JSON response
};
};
在 React 组件外部
🌐 Outside a React component
getFetchClient 可以在任何 JavaScript 环境中使用。典型的模式是将调用封装在导出的辅助函数内部,插件的其他部分再进行导入:
- JavaScript
- TypeScript
import { getFetchClient } from '@strapi/strapi/admin';
const { get, del } = getFetchClient();
export const fetchItems = async () => {
const { data } = await get('/my-plugin/items');
return data;
};
export const deleteItem = async (id) => {
await del(`/my-plugin/items/${id}`);
};
import { getFetchClient } from '@strapi/strapi/admin';
const { get, del } = getFetchClient();
export const fetchItems = async () => {
const { data } = await get('/my-plugin/items');
return data;
};
export const deleteItem = async (id: string) => {
await del(`/my-plugin/items/${id}`);
};
del 方法之所以这样命名,是因为 delete 在 JavaScript 中是保留字。
🌐 The del method is named this way because delete is a reserved word in JavaScript.
使用 post 和 put 发送数据
🌐 Sending data with post and put
post 和 put 方法将有效载荷作为它们的第二个参数:
🌐 The post and put methods accept a payload as their second argument:
- JavaScript
- TypeScript
import { getFetchClient } from '@strapi/strapi/admin';
const { post, put } = getFetchClient();
// Create a new item
export const createItem = async (payload) => {
const { data } = await post('/my-plugin/items', payload);
return data;
};
// Update an existing item
export const updateItem = async (id, payload) => {
const { data } = await put(`/my-plugin/items/${id}`, payload);
return data;
};
import { getFetchClient } from '@strapi/strapi/admin';
const { post, put } = getFetchClient();
// Create a new item
export const createItem = async (payload: Record<string, unknown>) => {
const { data } = await post('/my-plugin/items', payload);
return data;
};
// Update an existing item
export const updateItem = async (id: string, payload: Record<string, unknown>) => {
const { data } = await put(`/my-plugin/items/${id}`, payload);
return data;
};
在发送 FormData(例如,文件上传)时,fetch 客户端会自动移除 Content-Type 头,以便浏览器可以设置正确的多部分边界。
🌐 When sending FormData (for example, file uploads), the fetch client automatically removes the Content-Type header so the browser can set the correct multipart boundary.
配置请求
🌐 Configuring requests
所有方法都将选项对象作为最后一个参数:
🌐 All methods accept an options object as their last argument:
| 选项 | 类型 | 描述 |
|---|---|---|
params | object | 查询字符串参数。会自动序列化。 |
headers | Record<string, string> | 额外的请求头。会与默认值合并。 |
signal | AbortSignal | 用于取消请求。useFetchClient 会自动提供一个。 |
validateStatus | (status: number) => boolean | null | 自定义函数,用于决定哪些 HTTP 状态会抛出异常。 |
responseType | 'json' | 'blob' | 'text' | 'arrayBuffer' | 控制响应解析(见 响应类型)。仅在 get 上有效。 |
查询参数
🌐 Query parameters
传递 params 以自动序列化查询字符串:
🌐 Pass params to serialize query strings automatically:
const { data } = await get('/content-manager/collection-types/api::article.article', {
params: {
page: 1,
pageSize: 10,
sort: 'title:asc',
},
});
响应类型
🌐 Response types
默认情况下,响应会被解析为 JSON。get 方法接受一个 responseType 选项来处理非 JSON 响应,例如文件下载、CSV 导出或二进制数据:
🌐 By default, responses are parsed as JSON. The get method accepts a responseType option to handle non-JSON responses such as file downloads, CSV exports, or binary data:
responseType 值 | 解析后的响应 |
|---|---|
json | JSON 对象(默认) |
blob | Blob |
text | 纯文本字符串 |
arrayBuffer | ArrayBuffer |
非 JSON 响应在返回对象中包含 status 和 headers:
🌐 Non-JSON responses include status and headers in the return object:
- JavaScript
- TypeScript
import { useFetchClient } from '@strapi/strapi/admin';
const DownloadButton = () => {
const { get } = useFetchClient();
const downloadFile = async (url) => {
const { data: blob, status, headers } = await get(url, { responseType: 'blob' });
// Process the blob, for example to trigger a file download
};
};
import { useFetchClient } from '@strapi/strapi/admin';
const DownloadButton = () => {
const { get } = useFetchClient();
const downloadFile = async (url: string) => {
const { data: blob, status, headers } = await get(url, { responseType: 'blob' });
// Process the blob, for example to trigger a file download
};
};
处理错误
🌐 Handling errors
当请求失败时,fetch 客户端会抛出 FetchError。使用 isFetchError 工具可以安全地检查错误:
🌐 The fetch client throws a FetchError when a request fails. Use the isFetchError utility to check errors safely:
- JavaScript
- TypeScript
import { useFetchClient, isFetchError } from '@strapi/strapi/admin';
const MyComponent = () => {
const { get } = useFetchClient();
const fetchData = async () => {
try {
const { data } = await get('/my-plugin/my-endpoint');
// handle success
} catch (error) {
if (isFetchError(error)) {
// error.status contains the HTTP status code
console.error('Request failed:', error.status, error.message);
} else {
throw error; // re-throw non-fetch errors
}
}
};
};
import { useFetchClient, isFetchError } from '@strapi/strapi/admin';
const MyComponent = () => {
const { get } = useFetchClient();
const fetchData = async () => {
try {
const { data } = await get('/my-plugin/my-endpoint');
// handle success
} catch (error) {
if (isFetchError(error)) {
// error.status contains the HTTP status code
console.error('Request failed:', error.status, error.message);
} else {
throw error; // re-throw non-fetch errors
}
}
};
};
当请求返回 401 状态时,fetch 客户端会自动刷新身份验证令牌并在抛出错误之前重试该请求。此自动重试不适用于身份验证端点本身。
🌐 When a request returns a 401 status, the fetch client automatically refreshes the authentication token and retries the request before throwing an error. This automatic retry does not apply to authentication endpoints themselves.
👉 有关服务器端错误处理(控制器、服务、中间件),请参见 错误处理。