我正在尝试使用 slug 为带有 Strapi 后端的 React 博客获取帖子。 我创建了自定义路由和自定义 Controller ,但返回的值缺少一些属性,例如图像和类别。 当我使用 post Id 获取时,我使用查询字符串来填充返回的对象,但我不知道如何对 slug API 路由进行 qs。
下面是自定义 Controller 和自定义路由
///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
请注意我加了下划线,因为:
Routes files are loaded in alphabetical order. To load custom routes before core routes, make sure to name custom routes appropriately (e.g. 01-custom-routes.js and 02-core-routes.js).
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);
},
}));
- 现在您可以这样调用您的 api:
http://localhost:1337/api/articles/my-beautiful-article-about-orange
引用:https://www.youtube.com/watch?v=OVV0CfgX6Qk
注意:在视频中,custom.js 在 post.js 之前加载 ^^
关于javascript - 如何通过 slug 获取 Strapi,以及如何填充类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73261870/