-
Notifications
You must be signed in to change notification settings - Fork 114
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Gatsby Blog starter fails frontend #38
Comments
Same issue here on MacOS 12.3.1 I found 2 issues.
Creating a Strapi API token and setting the API endpoint to 127.0.0.1 in .env.development got me going. Hope this helps someone. |
Yea, adding in the .env.development in the frontend project with API token resolved it. Documentation should be updated to reflect that step. |
Yes the problem is that create-strapi-starter is not able to generate the API token required. It's mentioned in the readme:
|
Adding a bit of detail here...Attempting to use the Gatsby blog starter as documented here via The command is: The error produced is:
Work around:Here's how I was able to get it to work.
My system:
|
Scratch that. @connerxyz was right. Went the route of running BE and getting the API key etc and now I'm up and running. Thanks! |
@Jordan1022 @connerxyz I'm seeing the same issue and wasn't able to get a resolution.. I also followed the starter by running Then I ran @connerxyz's work around and got this error below
This issue was also happening when I was simply trying to get Strapi connected to another app. I'd be very thankful for any help! |
@jvmontes I found that the backend needs the following to get this starter to work.
I've found that replacing // backend/src/bootstrap.js
"use strict";
const fs = require("fs-extra");
const path = require("path");
const mime = require("mime-types");
const set = require("lodash.set");
const {
categories,
authors,
articles,
global,
about,
} = require("../data/data.json");
async function isFirstRun() {
const pluginStore = strapi.store({
environment: strapi.config.environment,
type: "type",
name: "setup",
});
const initHasRun = await pluginStore.get({ key: "initHasRun" });
await pluginStore.set({ key: "initHasRun", value: true });
return !initHasRun;
}
async function setInitPermissions(roleType, newPermissions) {
// Find the ID of the role
const role = await strapi
.query("plugin::users-permissions.role")
.findOne({
where: {
type: roleType,
},
});
// Create the new permissions and link them to the role
const allPermissionsToCreate = [];
Object.keys(newPermissions).map((controller) => {
const actions = newPermissions[controller];
const permissionsToCreate = actions.map((action) => {
return strapi.query("plugin::users-permissions.permission").create({
data: {
action: `api::${controller}.${controller}.${action}`,
role: role.id,
},
});
});
allPermissionsToCreate.push(...permissionsToCreate);
});
await Promise.all(allPermissionsToCreate);
}
async function setInitFrontendAPIToken(attributes) {
const apiTokenService = strapi.service(`admin::api-token`);
const apiToken = await apiTokenService.create(attributes);
const accessKey = apiToken.accessKey;
const credentialsLocation = process.env.FRONTEND_ENV_LOCATION || "frontend/.env.development"
fs.writeFile(credentialsLocation, `STRAPI_TOKEN=${accessKey}`, function (err) {
if (err) return console.log(err);
console.log('Frontend .env file updated.');
});
}
function getFileSizeInBytes(filePath) {
const stats = fs.statSync(filePath);
const fileSizeInBytes = stats["size"];
return fileSizeInBytes;
}
function getFileData(fileName) {
const filePath = path.join("data", "uploads", fileName);
// Parse the file metadata
const size = getFileSizeInBytes(filePath);
const ext = fileName.split(".").pop();
const mimeType = mime.lookup(ext);
return {
path: filePath,
name: fileName,
size,
type: mimeType,
};
}
async function uploadFile(file, name) {
return strapi
.plugin("upload")
.service("upload")
.upload({
files: file,
data: {
fileInfo: {
alternativeText: `An image uploaded to Strapi called ${name}`,
caption: name,
name,
},
},
});
}
// Create an entry and attach files if there are any
async function createEntry({ model, entry }) {
try {
// Actually create the entry in Strapi
await strapi.entityService.create(`api::${model}.${model}`, {
data: entry,
});
} catch (error) {
console.error({ model, entry, error });
}
}
async function checkFileExistsBeforeUpload(files) {
const existingFiles = [];
const uploadedFiles = [];
const filesCopy = [...files];
for (const fileName of filesCopy) {
// Check if the file already exists in Strapi
const fileWhereName = await strapi.query("plugin::upload.file").findOne({
where: {
name: fileName,
},
});
if (fileWhereName) {
// File exists, don't upload it
existingFiles.push(fileWhereName);
} else {
// File doesn't exist, upload it
const fileData = getFileData(fileName);
const fileNameNoExtension = fileName.split('.').shift()
const [file] = await uploadFile(fileData, fileNameNoExtension);
uploadedFiles.push(file);
}
}
const allFiles = [...existingFiles, ...uploadedFiles];
// If only one file then return only that file
return allFiles.length === 1 ? allFiles[0] : allFiles;
}
async function updateBlocks(blocks) {
const updatedBlocks = [];
for (const block of blocks) {
if (block.__component === "shared.media") {
const uploadedFiles = await checkFileExistsBeforeUpload([block.file]);
// Copy the block to not mutate directly
const blockCopy = { ...block };
// Replace the file name on the block with the actual file
blockCopy.file = uploadedFiles;
updatedBlocks.push(blockCopy);
} else if (block.__component === "shared.slider") {
// Get files already uploaded to Strapi or upload new files
const existingAndUploadedFiles = await checkFileExistsBeforeUpload(
block.files
);
// Copy the block to not mutate directly
const blockCopy = { ...block };
// Replace the file names on the block with the actual files
blockCopy.files = existingAndUploadedFiles;
// Push the updated block
updatedBlocks.push(blockCopy);
} else {
// Just push the block as is
updatedBlocks.push(block);
}
}
return updatedBlocks;
}
async function importArticles() {
for (const article of articles) {
const cover = await checkFileExistsBeforeUpload([`${article.slug}.jpg`]);
const updatedBlocks = await updateBlocks(article.blocks);
await createEntry({
model: "article",
entry: {
...article,
cover,
blocks: updatedBlocks,
// Make sure it's not a draft
publishedAt: Date.now(),
},
});
}
}
async function importGlobal() {
const favicon = await checkFileExistsBeforeUpload(["favicon.png"]);
const shareImage = await checkFileExistsBeforeUpload(["default-image.png"])
return createEntry({
model: "global",
entry: {
...global,
favicon,
// Make sure it's not a draft
publishedAt: Date.now(),
defaultSeo: {
...global.defaultSeo,
shareImage
}
},
});
}
async function importAbout() {
const updatedBlocks = await updateBlocks(about.blocks);
await createEntry({
model: "about",
entry: {
...about,
blocks: updatedBlocks,
// Make sure it's not a draft
publishedAt: Date.now(),
},
});
}
async function importCategories() {
for (const category of categories) {
await createEntry({ model: "category", entry: category });
}
}
async function importAuthors() {
for (const author of authors) {
const avatar = await checkFileExistsBeforeUpload([author.avatar]);
await createEntry({
model: "author",
entry: {
...author,
avatar,
},
});
}
}
async function importSeedData() {
// Initial demo permissions.
const initPermissions = {
article: ["find", "findOne"],
category: ["find", "findOne"],
author: ["find", "findOne"],
global: ["find", "findOne"],
about: ["find", "findOne"],
}
// Initialize public permissions.
await setInitPermissions("public", initPermissions)
// Initialize authenticated permissions.
await setInitPermissions("authenticated", initPermissions)
// Creating initial demo API token for the frontend.
await setInitFrontendAPIToken({
type: 'full-access',
name: 'full-access-demo',
description: 'Initial frontend demo token'
})
// Create all entries
await importCategories();
await importAuthors();
await importArticles();
await importGlobal();
await importAbout();
}
module.exports = async () => {
const shouldImportSeedData = await isFirstRun();
if (shouldImportSeedData) {
try {
console.log("Setting up the template...");
await importSeedData();
console.log("Ready to go");
} catch (error) {
console.log("Could not import seed data");
console.error(error);
}
}
}; |
@chadwcarlson thank you! So, here's what I had to do to get my app up and running. Follow @connerxyz 's work around. Before hitting step 4:
I follow @chadwcarlson lead and replace Thanks, finally can see the blog welcome screen! Cheers |
@connerxyz workaround worked for me. If you are using
|
None of these have helped me. I'm using the starter out of the box, but I'm still getting:
I've tried everything mentioned here and in other threads:
I'm feeling pretty stuck at this point. |
I've the same issues guys,
Now i'm not anymore stuck on the 403 but I've got the following error
for all templates of the starter kit : about.js, ... |
nevermind I found the issue when I looked at the global api -> 404 : http://localhost:1337/api/global |
I have the same issue |
3 of us spent a week on this issue with no luck. In the end we went with Contenful. :( Too bad because Strapi seemed to fit our needs better. |
I want use strapi in my project :( |
I don't think the problem is you. 🤷 |
You need to fill up the site info in the global collection from the admin ui
Le dim. 29 janv. 2023 à 20:12, Lance Snider ***@***.***> a
écrit :
… I want use strapi in my project :( I tested all of solutions above, but
did not fix. I don't know doing really
I don't think the problem is you. 🤷
—
Reply to this email directly, view it on GitHub
<#38 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAA4SWQTGHEO3D4RLCGZWP3WU26JNANCNFSM5T2W3VGA>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
Global is in the single types category, its fill by default |
I filled mine as well. |
fixed my issue |
I downgrade strapi version to 4.0.0 then its worked for me |
I keep getting GraphQLError: Unknown type "STRAPI__COMPONENT_SHARED_MEDIA". Did you mean "STRAPI__COMPONENT_SH upon executing my page query's but can't seem to find the cause. |
@Alex-Van-Dijck I am having the same error, any progress? |
Yes, had to work with another blog template without strapi sad enough. |
@Alex-Van-Dijck thank you for your quick feedback. Yes very sad. Normally we use Gatsby/Strapi or WP or Laravel, without GraphQl, with Rest API, I wanted to jump to GraphQL, but only it is giving a problems, so sad. |
@Alex-Van-Dijck I fixed, and it works for me const { strapiAbout } = useStaticQuery(graphql Change about for strapiAbout |
03.17.2024 and we haven't any solution? |
I've switched to nextjs far better and easier to customize
Le dim. 17 mars 2024, 11:13, Onur ***@***.***> a écrit :
… 03.17.2024 and we haven't any solution?
—
Reply to this email directly, view it on GitHub
<#38 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/AAA4SWSZF2TNLVNGXFUR7RTYYVUEZAVCNFSM5T2W3VGKU5DIOJSWCZC7NNSXTN2JONZXKZKDN5WW2ZLOOQ5TEMBQGIZTSMZSG4YQ>
.
You are receiving this because you commented.Message ID:
***@***.***>
|
Both approaches outlined in the doc for running the start successfully build and start the backend but fail to build the frontend.
OSX 12.1
node -v
v16.14.2
yarn -v
1.22.18
NPX output
npx.txt
YARN output
yarn.txt
The Next Blog starter works fine with either approach
The text was updated successfully, but these errors were encountered: