从使用Astro构建的单页面应用程序中获取最新的博客文章。

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年4月11日 12:00:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75982296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定