route.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { NextRequest, NextResponse } from "next/server";
  2. const BACKEND_HOST = process.env.NEXT_PUBLIC_BACKEND_HOST || "localhost";
  3. const BACKEND_PORT = process.env.NEXT_PUBLIC_BACKEND_PORT || "8080";
  4. const BACKEND_BASE = `http://${BACKEND_HOST}:${BACKEND_PORT}`;
  5. /** 开发环境:将 /api/agent/prompts 代理到后端,避免 rewrites 在 Turbopack 下不稳定 */
  6. export async function GET(request: NextRequest) {
  7. const { searchParams } = new URL(request.url);
  8. const backendUrl = `${BACKEND_BASE}/agent/prompts?${searchParams.toString()}`;
  9. const userID = request.headers.get("X-User-Id") || "";
  10. try {
  11. const res = await fetch(backendUrl, {
  12. cache: "no-store",
  13. headers: userID ? { "X-User-Id": userID } : {},
  14. });
  15. const body = await res.text();
  16. return new NextResponse(body, {
  17. status: res.status,
  18. headers: { "Content-Type": res.headers.get("content-type") || "application/json" },
  19. });
  20. } catch (e) {
  21. return NextResponse.json(
  22. { error: "无法连接后端,请确认后端已启动且端口一致(默认 8080)" },
  23. { status: 502 }
  24. );
  25. }
  26. }
  27. export async function PUT(request: NextRequest) {
  28. const backendUrl = `${BACKEND_BASE}/agent/prompts`;
  29. const userID = request.headers.get("X-User-Id") || "";
  30. try {
  31. const body = await request.text();
  32. const res = await fetch(backendUrl, {
  33. method: "PUT",
  34. headers: {
  35. "Content-Type": "application/json",
  36. ...(userID ? { "X-User-Id": userID } : {}),
  37. },
  38. body,
  39. });
  40. const resBody = await res.text();
  41. return new NextResponse(resBody, {
  42. status: res.status,
  43. headers: { "Content-Type": res.headers.get("content-type") || "application/json" },
  44. });
  45. } catch (e) {
  46. return NextResponse.json(
  47. { error: "无法连接后端,请确认后端已启动且端口一致(默认 8080)" },
  48. { status: 502 }
  49. );
  50. }
  51. }