You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Next.js API路由转换为Astro Endpoint?

Astro 访问量统计 Endpoint 实现

以下是适配 Astro 的访问量统计 API 代码,解决你提到的查询参数、内容类型获取及响应返回问题:

// src/pages/api/visit.ts
import { PrismaClient } from '@prisma/client';
import type { APIRoute } from 'astro';

const prisma = new PrismaClient();

export const GET: APIRoute = async ({ request }) => {
  // 1. 获取查询参数(替代 Next.js 的 request.query)
  const url = new URL(request.url);
  const slug = url.searchParams.get('slug');

  if (!slug) {
    return new Response(JSON.stringify({ error: '缺少 slug 参数' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  // 查询对应 slug 的访问量
  const stats = await prisma.visit.findUnique({
    where: { slug },
    select: { count: true },
  });

  // 返回 JSON 响应
  return new Response(JSON.stringify({ count: stats?.count || 0 }), {
    headers: { 'Content-Type': 'application/json' },
  });
};

export const POST: APIRoute = async ({ request }) => {
  // 2. 获取请求 Content-Type(替代 Next.js 的 request.body.contentType)
  const contentType = request.headers.get('Content-Type');

  if (!contentType || !contentType.includes('application/json')) {
    return new Response(JSON.stringify({ error: '仅支持 JSON 请求' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  const body = await request.json();
  const { slug } = body;

  if (!slug) {
    return new Response(JSON.stringify({ error: '缺少 slug 参数' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }

  // 更新或创建访问量记录
  await prisma.visit.upsert({
    where: { slug },
    update: { count: { increment: 1 } },
    create: { slug, count: 1 },
  });

  // 返回成功响应
  return new Response(JSON.stringify({ success: true }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
};

关键差异说明

  • 查询参数获取:Astro 没有 request.query,需通过 new URL(request.url).searchParams 解析 URL 查询字符串,用 get() 获取单个参数,getAll() 获取多值参数。
  • Content-Type 获取:请求的内容类型需从 request.headers.get('Content-Type') 读取,而非 Next.js 里的 request.body.contentType。
  • 响应返回:
    • 可以手动创建 Response 对象,指定响应体、状态码和头部;
    • 也可使用 Astro 内置的 json() 辅助函数简化 JSON 响应的创建:
      import { json } from 'astro';
      // ...
      return json({ success: true }, { status: 200 });
      

注意事项

  • 确保 Prisma Client 已正确初始化,生产环境建议使用单例模式避免过多数据库连接;
  • 根据你的数据模型调整 prisma.visit 的操作,比如表名或字段名不同需对应修改;
  • 可添加 try/catch 包裹数据库操作,捕获并返回更友好的错误信息。

内容的提问来源于stack exchange,提问作者Mathias Riis Sorensen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 10:42:19