<!-- Generated from zh/llms-txt-express/index.html. The canonical document is the HTML page. -->

- [ 首页 ](/zh/) 
/
- [ 如何创建 ](/zh/how-to-create/) 
/
- Express.js 指南            
# Express.js 的 `llms.txt`

Express 是最流行的 Node.js Web 框架。提供 llms.txt 很简单，可以用 express.static() 提供静态文件，或者用专门的 GET 路由动态生成。

最近更新: 2026年4月22日

本页内容

- [ 选项 1：使用 express.static() 提供静态文件 ](#static)
- [ 选项 2：专用 GET 路由 ](#route)
- [ TypeScript 版本 ](#typescript)
- [ 根据路由元数据动态生成 ](#dynamic)
- [ Cache-Control 标头 ](#cache)
- [ 验证 ](#verify)
- [ 发布前检查清单 ](#checklist)              
备注

应使用哪种方案？

使用  静态文件  方法，前提是你的  llms.txt  很少变化，并且您已使用  express.static() 。使用  GET 路由  如果 你想从数据库、CMS 或路由元数据动态生成内容。

## 选项 1：使用 express.static() 提供静态文件

如果你的应用已经使用 `express.static()` 来提供一个 `public/` 
文件夹，只需将 `llms.txt` 放入该文件夹。Express 将通过以下路径提供它： `/llms.txt` ，无需添加其他代码。
server.js, static file approach    复制     

```
// server.js
const express = require('express');
const app = express();

// Serve everything in ./public/ at the root URL.
// If public/llms.txt exists, it is available at /llms.txt automatically.
app.use(express.static('public'));

app.listen(3000, () => console.log('Listening on http://localhost:3000'));

// Project structure:
// your-express-app/
// ├── public/
// │   └── llms.txt   ← add this
// └── server.js

```

Express 会自动将 `Content-Type` 到 `text/plain` 
用于 `.txt` 通过以下方式提供的文件： `express.static()`。若要添加 `Cache-Control` 标头，请传入 `maxAge` 在静态选项中：
Cache-Control with express.static()    复制     

```
app.use(express.static('public', { maxAge: '1h' }));
```

## 选项 2：专用 GET 路由

如需完全控制标题和内容，请添加一个专用路由。当内容在运行时从数据库或你的 API
路由注册表生成时，这也是正确的 做法。
server.js, GET route    复制     

```
// server.js, dedicated GET route
const express = require('express');
const app = express();

const llmsContent = `# Your Site

> One-sentence description of what your site or product does.

## Documentation

- [Getting Started](https://yoursite.com/docs/start): Install and configure in minutes.
- [API Reference](https://yoursite.com/docs/api): Full endpoint catalog with examples.

## Product

- [Overview](https://yoursite.com/product): Core features and capabilities.
- [Pricing](https://yoursite.com/pricing): Plans and billing details.

## Optional

- [Changelog](https://yoursite.com/changelog): Release history.
- [GitHub](https://github.com/your-org/your-repo): Source code.
`;

app.get('/llms.txt', (req, res) => {
res.type('text/plain');
res.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
res.send(llmsContent);
});

app.listen(3000);

```

将此路由放在 **之前** 任何兜底路由处理器或 404 中间件，否则 Express 永远不会走到它。

## TypeScript 版本

如果项目使用 TypeScript 和 `@types/express`，请明确输入处理程序参数，以避免隐式 `any` 错误：
server.ts, TypeScript    复制     

```
// server.ts, TypeScript version with typed Request/Response
import express, { Request, Response } from 'express';

const app = express();

const llmsContent = `# Your Site

> One-sentence description of your product or service.

## Documentation

- [Getting Started](https://yoursite.com/docs/start): Quick setup guide.
- [API Reference](https://yoursite.com/docs/api): Full endpoint catalog.

## Optional

- [Changelog](https://yoursite.com/changelog): Release history.
`;

app.get('/llms.txt', (req: Request, res: Response): void => {
res.set({
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
});
res.send(llmsContent);
});

app.listen(3000, () => console.log('Server running on http://localhost:3000'));

```

## 根据路由元数据动态生成

对于较大型应用，请维护一个 `publicRoutes` 数组，并与路由定义放在一起。 `/llms.txt` 处理器会将这个数组映射为 Markdown 链接，确保文件与你的实际路由保持同步。
server.js, dynamic generation    复制     

```
// server.js, generate llms.txt dynamically from route metadata
const express = require('express');
const app = express();

// Define your public routes with metadata
const publicRoutes = [
{ title: 'Getting Started', path: '/docs/start', description: 'Install and configure in minutes.' },
{ title: 'API Reference', path: '/docs/api', description: 'Full endpoint catalog with examples.' },
{ title: 'Authentication', path: '/docs/auth', description: 'OAuth 2.0 and API key setup.' },
{ title: 'Webhooks', path: '/docs/webhooks', description: 'Event payloads and retry policy.' },
{ title: 'Pricing', path: '/pricing', description: 'Plans and billing details.' },
];

const SITE_URL = process.env.SITE_URL || 'https://yoursite.com';

app.get('/llms.txt', (req, res) => {
const links = publicRoutes
.map((r) => `- [${r.title}](${SITE_URL}${r.path}): ${r.description}`)
.join('\n');

const body = [
'# Your Site',
'',
'> One-sentence description of your product.',
'',
'## Documentation',
'',
links,
].join('\n');

res.set({
'Content-Type': 'text/plain; charset=utf-8',
'Cache-Control': 'public, max-age=3600, stale-while-revalidate=86400',
});
res.send(body);
});

app.listen(3000);

```

设置 `SITE_URL` 作为环境变量，使同一份代码可在本地、预发布和生产环境中运行。

## Cache-Control 标头

始终添加一个 `Cache-Control` 响应头。采用一小时 TTL 并配合 `stale-while-revalidate` 是一个合理的默认值，它允许反向代理和 CDN（nginx、 Cloudflare、AWS
CloudFront）缓存响应，并在后台重新验证时提供陈旧内容：
Recommended Cache-Control    复制     

```
res.set('Cache-Control', 'public, max-age=3600, stale-while-revalidate=86400');
```

如果你在 Express 前面使用 CDN，请确认该 CDN 会尊重 `Cache-Control` 从源站返回。Cloudflare 默认遵循该设置；AWS CloudFront 则需要配置允许源站响应头通过的缓存策略。

## 验证

启动服务器后，确认文件能正确提供：
Local verification    复制     

```
# Check headers
curl -I http://localhost:3000/llms.txt
# Expected:
# HTTP/1.1 200 OK
# Content-Type: text/plain; charset=utf-8
# Cache-Control: public, max-age=3600

# Check content
curl http://localhost:3000/llms.txt | head -5
# Should print:  # Your Site
```

部署后，对你的线上 URL 运行同样的检查，然后将其粘贴到 [llms.txt 验证器](/zh/validator/) 以检查是否完全符合规范。

## 发布前检查清单

- 文件提供于 `/llms.txt` 与 `200 OK`. 
- `Content-Type: text/plain; charset=utf-8` 已设置。 
- `Cache-Control` 标头存在。 
- 文件顶部只能有一个 H1 标题。 
- 紧接在 H1 后的引用块摘要。 
- 所有 URL 都是绝对的（`https://`). 
- 该路由注册在所有全匹配或 404 处理器之前。 
- 验证器未返回错误： [llmtxt.info/validator/](/zh/validator/)   
## 相关指南

- [如何创建 llms.txt](/zh/how-to-create/)、模板和检查清单。 
- [llms.txt 格式参考](/zh/llms-txt-format/)，规范细节。 
- [最佳实践](/zh/best-practices/)，应包含什么以及应跳过什么。 
- [验证器](/zh/validator/) · [生成器](/zh/generator/).        
## 来源

- [ llmstxt.org，社区提案 ](https://llmstxt.org/)
- [ Express.js 文档，express.static() ](https://expressjs.com/en/starter/static-files/)
- [ Express.js 文档，路由 ](https://expressjs.com/en/guide/routing/)
