1

Goal

I'm trying to retrieve data from the strapi API http://localhost:1337/articles but when I try to run an 11ty build I am given console errors (as can be seen below).

What I've tried

I've tried looking to see if anyone else has had the same issue and I can't seem to find anything. I've also looked at other people's strapi and 11ty setups to see if I had done something wrong with my general setup and all seems to be fine. The issue seems to be based on the connection between my blogposts.js file and the strapi data.

File being used to post data (blogposts.js)

const fetch = require("node-fetch");

// function to get blogposts
async function getAllBlogposts() {
    // max number of records to fetch per query
    const recordsPerQuery = 100;

    // number of records to skip (start at 0)
    let recordsToSkip = 0;

    let makeNewQuery = true;

    let blogposts = [];

    // make queries until makeNewQuery is set to false
    while (makeNewQuery) {
        try {
            // initiate fetch
            const data = await fetch("http://localhost:1337/articles", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Accept: "application/json",
                },
                body: JSON.stringify({
                    query: `{
              articles {
              id
              Title
              Content
              published_at
              Cover
              Slug
            }
          }`,
                }),
            });

            // store the JSON response when promise resolves
            const response = await data.json();

            // handle CMS errors
            if (response.errors) {
                let errors = response.errors;
                errors.map((error) => {
                    console.log(error.message);
                });
                throw new Error("Houston... We have a CMS problem");
            }

            // update blogpost array with the data from the JSON response
            blogposts = blogposts.concat(response.data.articles);

            // prepare for next query
            recordsToSkip += recordsPerQuery;

            // stop querying if we are getting back less than the records we fetch per query
            if (response.data.articles.length < recordsPerQuery) {
                makeNewQuery = false;
            }
        } catch (error) {
            throw new Error(error);
        }
    }

    // format blogposts objects
    const blogpostsFormatted = blogposts.map((item) => {
        return {
            id: item.id,
            title: item.Title,
            slug: item.Slug,
            body: item.Content,
            cover: item.Cover,
            date: item.published_at
        };
    });

    // return formatted blogposts
    return blogpostsFormatted;
}

// export for 11ty
module.exports = getAllBlogposts

Console Error after running npm

> TypeError: Cannot read property 'articles' of undefined

`Error` was thrown:
    Error: TypeError: Cannot read property 'articles' of undefined
        at getAllBlogposts (C:\Users\Kaleshe\kaleshe.github.io\_data\blogposts.js:62:19)        
        at processTicksAndRejections (internal/process/task_queues.js:93:5)
        at async TemplateData.getDataValue (C:\Users\Kaleshe\AppData\Roaming\npm-cache\_npx\11352\node_modules\@11ty\eleventy\src\TemplateData.js:385:23)
        at async TemplateData.getAllGlobalData (C:\Users\Kaleshe\AppData\Roaming\npm-cache\_npx\11352\node_modules\@11ty\eleventy\src\TemplateData.js:228:18)
        at async TemplateData.getData (C:\Users\Kaleshe\AppData\Roaming\npm-cache\_npx\11352\node_modules\@11ty\eleventy\src\TemplateData.js:255:24)

Strapi Console Error Message

debug POST /articles (9 ms) 403
  • Does this answer your question? [Strapi API calling error: {"statusCode":403,"error":"Forbidden","message":"Forbidden"}](https://stackoverflow.com/questions/53956118/strapi-api-calling-error-statuscode403-errorforbidden-messageforbi) – Eggcellentos Nov 15 '21 at 09:50

1 Answers1

2

Explaination:

Well 403 error response code corresponds to 403 - Forbidden. It means the route that you are trying to access, is simply not allowed to be accessed for your user role.

Now, looks at your request call, it is clear that you're not an authenticated user as you have not attached any bearer token on the api request. It shows you're probably trying to access a public api. But unfortunately, it's not marked as public in strapi settings.

Solution:

To get it working, you need to allow this api for the public role. You can do this by visiting the user-permissions module and editing the permissions for public role.

http://localhost:1337/admin/settings/users-permissions/roles

UI interface:

You should see an interface like below, where you can tick mark the apis that you require to be made public.

enter image description here

Reference:

Roles & Permissions

Salvino D'sa
  • 4,018
  • 1
  • 7
  • 19