英文:
Get most recent posts from a blog built with Astro in a Single Page Application
问题
Astro是否提供API以便从另一个应用程序轻松访问Astro博客的最新帖子?
英文:
I have one single page application where I would like to show most recent posts from Astro blog. Does astro provide an API to easily access such information from another application?
答案1
得分: 1
I used Astro Endpoints to create custom API for my blog.
src/pages/recent-posts.json.ts
import { MarkdownInstance } from "astro";
import { Frontmatter, sortDateDescending } from "src/misc";
export async function get() {
const allPosts = import.meta.glob<MarkdownInstance<Frontmatter>>("./posts/article/*.md", { eager: true }); // Vite
const posts = sortDateDescending(Object.values(allPosts))
.filter((ele) => ele.frontmatter.draft != true)
.map((ele) => {
return {
title: ele.frontmatter.title,
url: ele.url,
thumbnailUrl: ele.frontmatter.image,
content: ele.rawContent(),
publishedDate: ele.frontmatter.date,
tags: ele.frontmatter.tags,
};
});
const LIMIT = 2;
return {
body: JSON.stringify(posts.slice(0, LIMIT)),
};
}
Now, I can fetch the most recent posts from an endpoint /recent-posts.json
.
英文:
I used Astro Endpoints to create custom API for my blog.
src/pages/recent-posts.json.ts
import { MarkdownInstance } from "astro";
import { Frontmatter, sortDateDescending } from "src/misc";
export async function get() {
const allPosts = import.meta.glob<MarkdownInstance<Frontmatter>>("./posts/article/*.md", { eager: true }); // Vite
const posts = sortDateDescending(Object.values(allPosts))
.filter((ele) => ele.frontmatter.draft != true)
.map((ele) => {
return {
title: ele.frontmatter.title,
url: ele.url,
thumbnailUrl: ele.frontmatter.image,
content: ele.rawContent(),
publishedDate: ele.frontmatter.date,
tags: ele.frontmatter.tags,
};
});
const LIMIT = 2;
return {
body: JSON.stringify(posts.slice(0, LIMIT)),
};
}
Now, I can fetch the most recent posts from an endpoint /recent-posts.json
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论