Skip to main content

秘诀示例:自定义路由

¥Examples cookbook: Custom routes

Prerequisites

此页面是后端定制示例手册的一部分。请确保你已阅读其 introduction

¥This page is part of the back end customization examples cookbook. Please ensure you've read its introduction.

💭 上下文:

¥💭 Context:

开箱即用,FoodAdvisor 不控制对其内容类型端点的访问。

¥Out of the box, FoodAdvisor does not control access to its content-type endpoints.

假设我们 之前创建了一个策略 将对 "评论" 内容类型的访问限制在某些条件下,例如防止餐厅所有者为其餐厅创建评论。我们现在必须在用于创建评论的路由上启用策略。

¥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.

🎯 目标:

¥🎯 Goals:

  • 显式定义 "评论" 内容类型的路由配置。

    ¥Explicitly define a routes configuration for the "Reviews" content-type.

  • 将创建评论时使用的路由配置为:

    ¥Configure the route used when creating a review to:

🤓 Related concept

更多信息可在 政策路由 文档中找到。

¥Additional information can be found in the Policies and Routes documentation.

🧑‍💻 代码示例:

¥🧑‍💻 Code example:

FoodAdvisor 项目的 /api 文件夹中,将 api/src/api/review/routes/review.js 文件的内容替换为以下代码:

¥In the /api folder of the FoodAdvisor project, replace the content of the api/src/api/review/routes/review.js file with the following code:

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.