Question:
Why is contentText not returning blog posts content? api reference getPost
Product:
Wix Editor
What are you trying to achieve:
I want to get blog posts in plain text onto a webpage.
What have you already tried:
I created a backend JSW file with this code:
import { posts } from 'wix-blog-backend';
export async function getAllPostsContent() {
try {
const result = await posts.listPosts();
const postIds = result.posts.map(post => post._id);
return postIds;
} catch (error) {
console.error('Error fetching posts:', error);
throw error;
}
}
export async function getPostContent(postId) {
try {
const options = {
fieldsets: ['URL', 'CONTENT_TEXT'] // Specify the fieldsets to include 'CONTENT_TEXT'
};
const result = await posts.getPost(postId, options);
const contentText = result?.post?.contentText; // Check if contentText is defined
if (contentText !== undefined && contentText.trim() !== '') {
console.log(`Content text found for post ${postId}:`, contentText); // Log contentText
return contentText; // Return contentText if it's not empty
} else {
console.warn(`Content text not found or empty for post ${postId}`);
return null; // Return null to indicate that contentText is not available
}
} catch (error) {
console.error(`Error fetching content for post ${postId}:`, error);
throw error;
}
}
and the frontend code
import { getAllPostsContent, getPostContent } from 'backend/getBlogPosts'; // Importing the functions from the backend JSW file
// Function to fetch all posts content IDs from the backend
async function fetchAllPostsContentFromBackend() {
try {
const postIds = await getAllPostsContent();
console.log('All posts content IDs:', postIds);
// Fetch content for each post
for (const postId of postIds) {
try {
const contentText = await getPostContent(postId);
if (contentText !== null) { // Check if contentText is not null
console.log(`Content text for post ${postId}:`, contentText);
// Do something with the fetched content text
} else {
console.warn(`Content text not found or empty for post ${postId}`);
}
} catch (error) {
console.error(`Error fetching content for post ${postId}:`, error);
}
}
} catch (error) {
console.error('Error fetching all posts content from backend:', error);
}
}
// Call the function to fetch all posts content IDs from the backend
fetchAllPostsContentFromBackend();
Additional information:
however, the console log preview returns the following error message for every blog post ID - Content text not found or empty for post [ID]