2

I'm trying to fetch post for a react blog with strapi backend using the slug. I created the custom route and custom controller, but the value returned is missing a few attributes like images and category. When I fetch using post Id, I use query string to populate the object returned, but I don't know how to had qs to the slug API route.

Below is the custom controller, and the custom route

///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: []
        },

This is how I fetch from client in 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])

I've also tried to use the Entity API Service, but I just couldn't get it to work. How do I populate the object to include these missing attributes?

1
  • Have you tried using qs or stencil-qs? library you can use it in React but I most prefer to use stencil-qs it is what I am using for more info: medium.com/@nettisfabio/… Commented Jan 20, 2023 at 20:00

2 Answers 2

3

With Strapi v4 you can do it this way

1. Create a file in src/api/article/routes/_custom.js

Please note I put an underscore because:

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

Source: 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. Edit the 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. Now you can call your api this way:
    http://localhost:1337/api/articles/my-beautiful-article-about-orange

Reference: https://www.youtube.com/watch?v=OVV0CfgX6Qk
Note: In the video, custom.js is loaded before post.js ^^

Sign up to request clarification or add additional context in comments.

Comments

0

Very good idea about the underscore but on Strapi version 4.12.5 unfortunately it doesn't work as expected so you need to put a number in front of your custom.js file.

Also, you can go without the custom.js file in the routes folder if in your article.js file instead of this const { slug } = ctx.params; you have this const { id: slug } = ctx.params;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.