服务器 API:路由
🌐 Server API: Routes
Page summary:
服务器 API 从服务器入口文件导出一个
routes值以公开插件端点。仅对隐式管理路由使用数组格式,使用命名路由格式分离管理和内容 API 路由,或使用工厂回调格式进行动态路由配置。
路由会公开你的插件的 HTTP 端 点,并将传入请求映射到控制器操作。它们从 服务器入口文件 导出,作为一个 routes 值。
🌐 Routes expose your plugin's HTTP endpoints and map incoming requests to controller actions. They are exported from the server entry file as a routes value.
在深入了解本页的概念之前,请确保你已经:
🌐 Before diving deeper into the concepts on this page, please ensure you have:
- 创建了一个 Strapi 插件,
- 已阅读并理解了服务器 API的基础知识
路由声明格式
🌐 Route declaration formats
数组格式
🌐 Array format
数组格式是最基本的格式:它直接导出路由对象的数组。Strapi 默认将这些对象注册为管理路由,插件名称作为前缀。
🌐 The array format is the most basic format: it exports an array of route objects directly. Strapi registers these objects as admin routes by default, with the plugin name as prefix.
要公开内容 API 路由,请使用带有 type: 'content-api' 的命名路由格式。
🌐 To expose Content API routes, use the named router format with type: 'content-api'.
- JavaScript
- TypeScript
'use strict';
module.exports = [
{
method: 'GET',
path: '/articles',
handler: 'article.find',
config: {
policies: [],
},
},
{
method: 'POST',
path: '/articles',
handler: 'article.create',
config: {
policies: [],
},
},
];
export default [
{
method: 'GET',
path: '/articles',
handler: 'article.find',
config: {
policies: [],
},
},
{
method: 'POST',
path: '/articles',
handler: 'article.create',
config: {
policies: [],
},
},
];
命名路由格式
🌐 Named router format
使用命名路由格式时,使用具有命名键(admin、content-api 或任何自定义名称)的对象来声明单独的路由组。每个组都是一个路由对象,包含 type、可选的 prefix 和一个 routes 数组。当你的插件同时暴露管理和内容 API 路由时使用此格式。
🌐 With the named router format, use an object with named keys (admin, content-api, or any custom name) to declare separate router groups. Each group is a router object with a type, optional prefix, and a routes array. Use this format when your plugin exposes both admin and Content API routes.
- JavaScript
- TypeScript
'use strict';
const adminRoutes = require('./admin');
const contentApiRoutes = require('./content-api');
module.exports = {
admin: adminRoutes,
'content-api': contentApiRoutes,
};
'use strict';
module.exports = {
type: 'admin',
routes: [
{
method: 'GET',
path: '/articles',
handler: 'article.find',
config: {
policies: ['admin::isAuthenticatedAdmin'],
},
},
],
};
'use strict';
module.exports = {
type: 'content-api',
routes: [
{
method: 'GET',
path: '/articles',
handler: 'article.find',
config: {
policies: [],
},
},
],
};
import adminRoutes from './admin';
import contentApiRoutes from './content-api';
export default {
admin: adminRoutes,
'content-api': contentApiRoutes,
};
export default {
type: 'admin' as const,
routes: [
{
method: 'GET' as const,
path: '/articles',
handler: 'article.find',
config: {
policies: ['admin::isAuthenticatedAdmin'],
},
},
],
};
export default {
type: 'content-api' as const,
routes: [
{
method: 'GET' as const,
path: '/articles',
handler: 'article.find',
config: {
policies: [],
},
},
],
};