Strapi中如何根据自定义后端值修改投票接口响应
Strapi投票接口时段限制:返回指定禁止响应的实现方案
核心实现逻辑
在你已配置的中间件中,先查询votingPeriod单类型的配置数据,根据isVotingAllowed字段的值拦截请求:
完整中间件代码
假设中间件文件为src/middlewares/vote-restriction.js,代码如下:
module.exports = (config, { strapi }) => { return async (ctx, next) => { // 查询投票时段配置 const votingConfig = await strapi.db.query('api::voting-period.voting-period').findOne(); if (votingConfig?.isVotingAllowed) { // 允许投票,放行至后续流程 await next(); } else { // 禁用投票时,返回指定响应 ctx.status = 403; ctx.body = { message: "voting currently not allowed" }; } }; };
关键细节说明
- 单类型查询路径:Strapi v4中,单类型的查询格式为
strapi.db.query('api::[单类型名称转短横线].[单类型名称转短横线]').findOne(),如果你的单类型定义为votingPeriod,则路径是api::voting-period.voting-period。 - HTTP状态码:使用
403 Forbidden状态码,符合“操作被禁止”的语义;若需适配业务需求,也可改用400 Bad Request。 - 路由绑定验证:确保中间件已绑定到投票创建接口(POST
/api/votes),比如在src/api/vote/routes/vote.js中配置:
module.exports = { routes: [ { method: 'POST', path: '/votes', handler: 'vote.create', config: { middlewares: ['global::vote-restriction'], // 全局中间件写法;局部中间件则用'api::vote.vote-restriction' }, }, ], };
内容的提问来源于stack exchange,提问作者derelektrischemoench
相关产品推荐
相关产品推荐

