跳到主要内容
Ed. notes

05 服务端接口:内容如何离开文件系统

长文 · 2026-11-12 · 合集第 6 / 10 篇

  • Nitro
  • API
  • Markdown
  • 构建日志
第 6 / 10 篇 · 查看全部章节 → 当前:05 服务端接口:内容如何离开文件系统

结论

内容层只返回内存里的 ContentNote,浏览器不能直接读它。中间需要一层 HTTP 接口:

路径 作用 数据来源
/api/notes 列表、标签、系列 loadContent() 后的聚合结果
/api/notes/[slug] 单篇详情和渲染后的 HTML loadContent() + 渲染
/content-assets/{section}/{slug}/... 本地图片资源 文章目录内的文件
/rss.xml RSS 2.0 订阅 已发布内容
/sitemap.xml 站点地图 已发布内容
/api/health 健康检查和内容数量 内容层

这一层的原则是「薄」:不重新实现业务规则,只调用内容层、组织响应、处理 404 和缓存头。所有内容合法性判断仍然只有一份。

问题与设计

列表接口一次返回三块数据

目录页同时需要笔记、标签和系列。如果拆成三个请求,页面要处理三个加载状态和三个错误状态;当前数据量很小,合并成一个响应更简单:

{
  "notes": [],
  "tags": [],
  "series": []
}

标签和系列不是单独存储的,而是每次从已发布内容聚合出来。这样新增一篇文章、改一个 series 字段,不需要维护第二份索引。

详情在服务端渲染 Markdown

详情接口返回 html,而不是让浏览器下载 Markdown 再解析:

  • 客户端不需要打包 markdown-it;
  • 页面首屏就有正文,SEO 和阅读体验更稳定;
  • 渲染规则只有一份,图片路径改写也在服务端完成。

Markdown 实例关闭了原始 HTML:

const markdown = new MarkdownIt({ html: false, linkify: true })

内容来自仓库内的 Markdown,但「仓库内」不等于「绝对可信」;关闭 html 让正文不能注入脚本。页面上的 v-html 因此只承载受控的 Markdown 输出。

图片路径在渲染时改写

正文里写的是相对路径:

![状态图](./images/02-states.png)

服务端把它改成站点路径:

/content-assets/articles/build-log-02-architecture/images/02-states.png

改写时做三件事:拒绝 ..、绝对路径和反斜杠;对每一段做 encodeURIComponent;根据内容类型选择 notes 或 articles 前缀。图片路由再做一次目录边界检查,防止路径穿越。

资源路由和内容路由共享发布规则

图片路由同样调用 loadContent(),所以只有已发布内容能访问对应资源。草稿文章的图片在生产环境不可见,这和草稿不出现在目录、RSS、sitemap 中保持一致。

关键代码

列表接口

// frontend/server/api/notes/index.get.ts
export default defineEventHandler(() => {
  const contentDir = String(useRuntimeConfig().contentDir)
  const notes = loadContent({ contentDir })
  const summaries = notes.map(toNoteSummary)

  return {
    notes: summaries,
    tags: aggregateTags(summaries),
    series: aggregateSeries(summaries),
  }
})

详情接口

详情接口除了正文和标题锚点,还返回同系列的完整章节列表和上下篇,文章页据此渲染系列导航和翻页:

// frontend/server/api/notes/[slug].get.ts
export default defineEventHandler((event) => {
  const slug = getRouterParam(event, 'slug')

  if (!slug) {
    throw createError({ statusCode: 404, statusMessage: '笔记不存在' })
  }

  const contentDir = String(useRuntimeConfig().contentDir)
  const notes = loadContent({ contentDir })
  const note = notes.find((item) => item.slug === slug)

  if (!note) {
    throw createError({ statusCode: 404, statusMessage: '笔记不存在' })
  }

  const { html, headings } = renderMarkdown(note)
  const series = note.series
    ? aggregateSeries(notes.map(toNoteSummary)).find((item) => item.name === note.series)
    : undefined

  const currentIndex = series ? series.notes.findIndex((item) => item.slug === note.slug) : -1

  return {
    note: {
      ...toNoteSummary(note),
      html,
      headings,
    },
    // 左侧系列导航需要同系列的完整章节列表。
    chapters: series?.notes ?? [],
    prev: currentIndex > 0 ? series?.notes[currentIndex - 1] : undefined,
    next: currentIndex >= 0 && series ? series.notes[currentIndex + 1] : undefined,
  }
})

上下篇按阅读序号计算,且只包含已发布内容;草稿既不出现在 chapters 里,也不影响前后篇的指向。

Markdown 渲染与图片改写

markdown.renderer.rules.image = (tokens, index, options, environment, self) => {
  const token = tokens[index]
  if (!token) return ''

  const source = token.attrGet('src')
  if (source !== null) {
    token.attrSet(
      'src',
      resolveImageSource(
        String(environment?.slug ?? ''),
        String(source),
        environment?.kind === 'article' ? 'article' : 'note',
      ),
    )
  }

  token.attrSet('loading', 'lazy')
  token.attrSet('decoding', 'async')

  return defaultImageRenderer(tokens, index, options, environment, self)
}

export const renderMarkdown = (
  note: Pick<ContentNote, 'slug' | 'body'> & { kind?: ContentKind },
): string => markdown.render(note.body, { slug: note.slug, kind: note.kind ?? 'note' })

图片路由的边界检查

// frontend/server/routes/content-assets/[...path].get.ts
const section = segments[0]
const slug = segments[1]!
const kind = section === 'articles' ? 'article' : 'note'
const contentDir = String(useRuntimeConfig().contentDir)
const entry = loadContent({ contentDir }).find((item) => item.slug === slug && item.kind === kind)

if (!entry) throw notFound()

const assetDir =
  kind === 'article' ? dirname(resolve(contentDir, entry.file)) : resolve(contentDir, 'notes', slug)
const assetPath = resolve(assetDir, ...segments.slice(2))

if (assetPath !== assetDir && !assetPath.startsWith(assetDir + sep)) throw notFound()

响应还会设置 X-Content-Type-Options: nosniff。生产环境的 Cache-Control 是长缓存加 immutable,因为图片路径和内容一起版本化;开发环境则禁用缓存,方便替换图片。

RSS 和 sitemap

两者都不手写第二套内容查询,直接调用 loadContent():

// frontend/server/routes/sitemap.xml.get.ts
const notes = loadContent({ contentDir: String(useRuntimeConfig().contentDir) })

const urls = [
  { loc: `${siteUrl}/`, lastmod: undefined },
  { loc: `${siteUrl}/notes`, lastmod: notes[0]?.date },
  { loc: `${siteUrl}/about`, lastmod: undefined },
  ...notes.map((note) => ({ loc: `${siteUrl}/notes/${note.slug}`, lastmod: note.date })),
]

RSS 的每一项使用文章标题、摘要、链接和日期;XML 文本统一经过 escapeXml()。站点 URL 来自 NUXT_PUBLIC_SITE_URL,部署时必须配置成真实域名,否则订阅和 sitemap 会写死 localhost。

健康检查

// frontend/server/api/health.get.ts
export default defineEventHandler(() => {
  const entries = loadContent({ contentDir: String(useRuntimeConfig().contentDir) })
  return { status: 'ok', notes: entries.length }
})

它同时验证了内容目录可读、内容能通过校验。Docker 的 HEALTHCHECK 和 Caddy 的启动依赖都用这个接口。

验证

启动开发服务器后,从接口层往上检查:

curl -s http://localhost:3000/api/notes | head -c 400
curl -s http://localhost:3000/api/notes/build-log-01-background-scope | head -c 400
curl -s http://localhost:3000/api/health
curl -s http://localhost:3000/rss.xml | head -20
curl -s http://localhost:3000/sitemap.xml | head -20

再验证 404:

curl -i http://localhost:3000/api/notes/does-not-exist

预期是 404,而不是空对象或 500。最后打开一篇带本地图片的文章,确认图片地址以 /content-assets/ 开头,并且请求返回正确的 Content-Type。

边界

  • 接口没有鉴权,因为博客内容本来就是公开的;AI 的 /api/chat 是另一条链路,默认关闭且需要额外保护。
  • 没有分页、搜索和 ETag;每次请求都重新读取内容。当前规模下这不是瓶颈。
  • 图片只允许白名单扩展名,且只对已发布内容生效;草稿文章的图片在所有环境下都不可访问。
  • RSS 和 sitemap 在请求时生成,不写静态文件;内容更新后需要重新构建或重启服务。
  • siteUrl 配置错误会让 canonical、RSS 和 sitemap 一起出错,部署前先检查 NUXT_PUBLIC_SITE_URL。
  • 更细的资源缓存、部署和 CDN 策略在 构建实践。

下一篇进入浏览器侧:页面怎样调用这些接口,把 JSON 变成首页、目录、详情和系列总览。