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