29 lines
1011 B
JavaScript
29 lines
1011 B
JavaScript
// Function to fetch and display posts
|
|
async function fetchAndDisplayPosts() {
|
|
try {
|
|
const response = await fetch("http://localhost:1337/api/posts"); // Adjust URL to your Strapi server
|
|
const result = await response.json();
|
|
|
|
const postsContainer = document.getElementById("posts-container");
|
|
postsContainer.innerHTML = ""; // Clear any existing content
|
|
|
|
// Loop through the posts and create links
|
|
result.data.forEach((post) => {
|
|
const postElement = document.createElement("div");
|
|
const postLink = document.createElement("a");
|
|
|
|
// Link to the post (using slug or id for dynamic routes)
|
|
postLink.href = `/posts/${post.attributes.slug}`; // Adjust this to match your route
|
|
postLink.textContent = post.attributes.title;
|
|
|
|
postElement.appendChild(postLink);
|
|
postsContainer.appendChild(postElement);
|
|
});
|
|
} catch (error) {
|
|
console.error("Error fetching posts:", error);
|
|
}
|
|
}
|
|
|
|
// Fetch posts when the page loads
|
|
document.addEventListener("DOMContentLoaded", fetchAndDisplayPosts);
|