示例手册:自定义路由
🌐 Examples cookbook: Custom routes
Page summary:自定义路由让你可以明确配置内容类型的路由,以控制身份验证并应用策略,例如绕过默认的 Strapi 身份验证或根据自定义条件限制访问。
🌐 Custom routes let you explicitly configure routes for content-types to control authentication and apply policies, such as bypassing default Strapi authentication or restricting access based on custom conditions.
这些示例是围绕 FoodAdvisor构建的,而 FoodAdvisor不再是Strapi的特色演示应用(它已被 LaunchPad取代)。这里重要的是理解所展示的后端机制,而不是FoodAdvisor本身。这些页面将被重新访问以使用LaunchPad。
此页面是后端自定义示例手册的一部分。请确保你已阅读其介绍。
🌐 This page is part of the back end customization examples cookbook. Please ensure you've read its introduction.
💭 上下文:
开箱即用时, FoodAdvisor 不会控制对其内容类型端点的访问。
假设我们之前创建了一个策略来限制对“评论”内容类型的访问某些条件,例如防止餐厅老板为他们的餐厅创建评论。我们现在必须在用于创建评论的路由上启用该策略。
🌐 Let's say we previously created a policy to restrict access to the "Reviews" content-type to some conditions, for instance to prevent a restaurant's owner to create a review for their restaurants. We must now enable the policy on the route we use to create reviews.
🎯 目标:
- 明确定义“Reviews”内容类型的路由配置。
- 将创建评论时使用的路由配置为:
- 绕过默认的 Strapi 身份验证系统
- 并根据先前定义的自定义策略限制访问。
🧑💻 代码示例:
在 FoodAdvisor 项目的 /api 文件夹中,将 api/src/api/review/routes/review.js 文件的内容替换为以下代码:
'use strict';
const { createCoreRouter } = require('@strapi/strapi').factories;
module.exports = createCoreRouter('api::review.review', {
config: {
create: {
auth: false, // set the route to bypass the normal Strapi authentication system
policies: ['is-owner-review'], // set the route to use a custom policy
middlewares: [],
},
},
});
了解更多关于如何配置自定义中间件以执行扩展你的 Strapi 应用的附加操作的信息。
🌐 Learn more about how to configure custom middlewares to perform additional actions that extend your Strapi-based application.