如何通过slug获取Strapi,以及如何填充类别



我正试图使用slug为一个带有strapi后端的react博客获取帖子。我创建了自定义路由和自定义控制器,但返回的值缺少一些属性,如图像和类别。当我使用post-Id获取时,我使用查询字符串来填充返回的对象,但我不知道如何将qs发送到slug API路由。

下面是自定义控制器和自定义路线

///custom controller
async findOne(ctx) {
const { slug } = ctx.params;
const { query } = ctx;

const entity = await strapi.service('api::article.article').findOne(slug, query);
const sanitizedEntity = await this.sanitizeOutput(entity, query);
return this.transformResponse(sanitizedEntity);
}
///Custom Route
{
method: 'GET',
path: '/articles/slug/:slug',
handler: 'custom-controller.findOne',
config: {
policies: []
},

这是我在useEffect 中从客户端获取的方式


useEffect(()=>{
const fetchData = async()=>{
// const query = qs.stringify({
//     populate: '*', 
//     }, {
//     encodeValuesOnly: true,
//     });
const res = await axios.get(`http://localhost:1337/api/articles?filters[slug][$eq]=${slug}`)
console.log(res.data)
updateState(res.data) 

}
fetchData()
setLoading(false)
},  [slug])

我也尝试过使用实体API服务,但就是无法使其工作。如何填充对象以包含这些缺失的属性?

使用Strapi v4,您可以通过这样做

1.在src/api/article/routes/_custom.js中创建文件

请注意,我放了一个下划线,因为:

按字母顺序加载路由文件。要在核心路由之前加载自定义路由,请确保适当地命名自定义路由(例如01-customizedroutes.js和02-core-routes.js(。

来源:https://docs.strapi.io/developer-docs/latest/development/backend-customization/routes.html#creating-自定义路由器

module.exports = {
routes: [
{
method: 'GET',
path: '/articles/:slug',
handler: 'article.findOne',
config: {
auth: false
},
}
]
}

2.编辑src/api/article/controllers/article.js

'use strict';
/**
* article controller
*/
const { createCoreController } = require('@strapi/strapi').factories;
module.exports = createCoreController('api::article.article', ({ strapi }) => ({
// Query by slug
async findOne(ctx) {
// thanks to the custom route we have now a slug variable
// instead of the default id
const { slug } = ctx.params;
const entity = await strapi.db.query('api::article.article').findOne({
where: { slug }
});
const sanitizedEntity = await this.sanitizeOutput(entity, ctx);
return this.transformResponse(sanitizedEntity);
},
}));
  1. 现在您可以通过以下方式调用您的api:
    http://localhost:1337/api/articles/my-beautiful-article-about-orange

参考:https://www.youtube.com/watch?v=OVV0CfgX6Qk
注意:在视频中,custom.js在post.js^^之前加载

关于下划线的想法很好,但不幸的是,在Strapi 4.12.5版本上,它无法按预期工作,因此您需要在custom.js文件前面放一个数字。

此外,如果在article.js文件而不是这个const { slug } = ctx.params;中有这个const { id: slug } = ctx.params;,则可以在routes文件夹中不使用custom.js文件

最新更新