Skip to content

Commit 9b0fcf7

Browse files
committed
fix: rewrite 避免CORS错误
1 parent 6f40726 commit 9b0fcf7

2 files changed

Lines changed: 11 additions & 7 deletions

File tree

lib/use-auth.tsx

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,14 +33,11 @@ function getStoredToken(): string | null {
3333
return localStorage.getItem("satoken");
3434
}
3535

36-
// 后端地址(浏览器直接访问,Next.js public env var)
37-
const BACKEND_URL =
38-
process.env.NEXT_PUBLIC_BACKEND_URL ?? "http://localhost:8080";
39-
4036
// 调用后端 /auth/me 验证 token 并获取用户信息
37+
// 走 Next.js rewrite(/auth/* → 后端),浏览器无跨域问题
4138
async function fetchCurrentUser(token: string): Promise<UserView | null> {
4239
try {
43-
const res = await fetch(`${BACKEND_URL}/auth/me`, {
40+
const res = await fetch("/auth/me", {
4441
headers: { satoken: token },
4542
});
4643
if (!res.ok) return null;
@@ -98,7 +95,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
9895
const token = getStoredToken();
9996
if (token) {
10097
try {
101-
await fetch(`${BACKEND_URL}/auth/logout`, {
98+
// 走 Next.js rewrite,同源请求
99+
await fetch("/auth/logout", {
102100
method: "POST",
103101
headers: { satoken: token },
104102
});

next.config.mjs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,17 @@ const config = {
2525
const backendUrl = process.env.BACKEND_URL ?? "http://localhost:8080";
2626
return [
2727
{
28-
// GitHub OAuth 回调:GitHub 重定向到 Next.js,Next.js 再转发给后端
28+
// GitHub OAuth 回调:GitHub → localhost:3000/api/auth/callback/github → 后端
2929
// 路径与 GitHub OAuth App 注册的 callback URL 保持一致,无需改 GitHub App 设置
3030
source: "/api/auth/callback/github",
3131
destination: `${backendUrl}/api/auth/callback/github`,
3232
},
33+
{
34+
// 认证 API(/auth/me, /auth/logout 等)走 Next.js 代理,避免浏览器跨域 CORS 问题
35+
// 浏览器只见 localhost:3000,Next.js 服务端再转发给 localhost:8080
36+
source: "/auth/:path*",
37+
destination: `${backendUrl}/auth/:path*`,
38+
},
3339
];
3440
},
3541
images: {

0 commit comments

Comments
 (0)