Astro 服务端端点
什么是端点
端点(Endpoint)就是「在 src/pages/ 下用代码返回响应、而不是返回 HTML 页面」的文件。
它可以输出 JSON、XML,甚至图片,常用于提供接口、生成站点地图、RSS(Astro 站点配置与 SEO)等。
创建一个 JSON 接口
在 src/pages/api/ 下放一个 .ts 文件,导出一个处理函数。
// src/pages/api/hello.ts
import type { APIRoute } from 'astro'; // APIRoute 是端点的类型,约束处理函数签名
export const GET: APIRoute = () => {
// 返回 JSON 响应,需手动指定 Content-Type
return new Response(
JSON.stringify({ message: 'hello from astro' }),
{ headers: { 'Content-Type': 'application/json' } }
);
};
访问 /api/hello 就能拿到这段 JSON。
读取请求参数
处理函数接收 request、params、url 等上下文。
export const GET: APIRoute = ({ url }) => {
const name = url.searchParams.get('name') ?? '访客'; // 读取 ?name= 查询参数,没有则默认访客
return new Response(JSON.stringify({ name }));
};
访问 /api/hello?name=小明 会得到 {"name":"小明"}。
处理不同方法
同一个文件可以导出 GET、POST 等多个方法。
export const POST: APIRoute = async ({ request }) => {
const body = await request.json(); // 读取 POST 请求体并解析为 JSON
return new Response(JSON.stringify({ received: body }), {
status: 200,
});
};
输出非 JSON 内容
端点不限于 JSON,比如生成一个纯文本站点地图片段。
export const GET: APIRoute = () => {
// 输出 XML,常用于站点地图片段
return new Response('<urlset>...</urlset>', {
headers: { 'Content-Type': 'application/xml' },
});
};
在静态站点的限制
默认静态构建下,端点会在构建时执行一次、生成固定文件,如果你需要「每次请求都实时计算」,需要把站点部署为 SSR/按需渲染模式(Astro 部署 里配置 output: 'server' 或对应适配器)。