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

标签 javascript reactjs strapi

我正在尝试使用 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).

来源:https://docs.strapi.io/developer-docs/latest/development/backend-customization/routes.html#creating-custom-routers

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/

    相关文章:

    reactjs - 单元测试 React Native : NativeModules. RNViewShot 未定义。确保库在 native 端链接

    reactjs - 避免 React 中的登录表单闪烁

    javascript - Sencha touch - 是否可以在客户端存储大型数据库

    javascript - For循环不打印所有数组

    javascript - 类内的 CSS id

    javascript - 如何在 React.JS 中更改登录/注销时的 NavBar 文本?

    reactjs - 如何在 react 数据网格中创建自定义行渲染器

    javascript - 在 GridFS、express、mongoDB、node.js 中存储来自 POST 请求的数据流

    postgresql - 是否可以将现有数据库与 Strapi CMS 连接?

    session-cookies - 在 Strapi 中启用用户 session