From 5e402948a2dfaf4c18fb3f07be2a1f88aae722a2 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 29 Dec 2025 01:34:30 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E4=B8=AD=E9=97=B4?= =?UTF-8?q?=E4=BB=B6=E5=AF=B9API=20POST=E8=AF=B7=E6=B1=82=E7=9A=84?= =?UTF-8?q?=E9=94=99=E8=AF=AF=E9=87=8D=E5=AE=9A=E5=90=91=EF=BC=8C=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E8=BF=94=E5=9B=9E401=E8=80=8C=E4=B8=8D=E6=98=AF?= =?UTF-8?q?=E9=87=8D=E5=AE=9A=E5=90=91=E5=88=B0=E7=99=BB=E5=BD=95=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/middleware.ts b/middleware.ts index f600944..20b9534 100644 --- a/middleware.ts +++ b/middleware.ts @@ -90,6 +90,15 @@ export async function middleware(request: NextRequest) { // 未登录用户只能访问 /login 和 /register if (!token && !["/login", "/register"].includes(pathname)) { + // 对于 API 路由的非 GET 请求,直接返回 401 JSON 响应(不重定向) + if (pathname.startsWith("/api/") && request.method !== "GET") { + return NextResponse.json( + { error: "未授权,请先登录" }, + { status: 401 } + ); + } + + // 对于页面路由(GET 请求),重定向到登录页面 const loginUrl = new URL("/login", externalBase); // 保存当前路径作为回调 URL loginUrl.searchParams.set("callbackUrl", pathname);