供您参考,我是编程新手。
背景: 我正在为我的应用程序创建身份验证。我在后端使用 NextJS 14 以及 AppRouter 和 laravel 来管理令牌。我在 nextJS 中创建了一个函数,它只是通过使用 fetchAPI 向 laravel 端点发送请求来检查用户是否已通过身份验证,如果响应不正常(即 401(未经授权)),则应将用户重定向到主页(即“/”)。
错误: 当我尝试使用 NextJS 函数“redirect()”时。它抛出一个错误:
Error: NEXT_REDIRECT
我的代码:
import { redirect } from "next/navigation";
import { hasCookie } from "cookies-next";
import { cookies } from "next/headers";
import { BASE_URL, API_ENDPOINTS } from "@/app/data/api";
export default function useAuth() {
const existingToken = hasCookie("token", { cookies }); // returns 'true' if the token exists
console.log("existing token?", existingToken);
const cookiesSet = cookies();
const checkUser = async () => {
if (existingToken) {
const token = cookiesSet.get("token").value; // returns the token from cookies
console.log("the token: ", token);
try {
const response = await fetch(
`${BASE_URL}${API_ENDPOINTS.PROFILE_DETAILS}`,
{
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
}
);
if (!response.ok) {
console.log("User is not authenticated, response not ok");
redirect("/"); // The issue is here. It does not redirect
}
} catch (error) {
console.error("Error:", error.message);
}
}
};
checkUser();
return null; // Return null to avoid rendering any content
}
注意: 我希望在服务器端实现此重定向功能。
我想要实现的目标: 我想为服务器端重定向创建一个通用函数。每当我在任何 page.jsx 中调用它时。它应该检查用户是否未经授权,然后应该将其重定向到主页。
我尝试了什么 我尝试使用“useRouter”完成任务,但后来发现它只适用于客户端。我徘徊了两天才得到解决方案。即使 ChatGPT 也无法帮助我。
您似乎正在客户端上调用
redirect()
。 redirect
仅在服务器上使用,doc说:
重定向功能允许您将用户重定向到另一个 URL。重定向可用于服务器组件、路由处理程序和服务器操作。
useRouter
来代替,如下所示:
// ...
import { useRouter } from "next/navigation";
export default function useAuth() {
//..
const router = useRouter();
const checkUser = async () => {
if (existingToken) {
//...
try {
const response = await fetch(`${BASE_URL}${API_ENDPOINTS.PROFILE_DETAILS}`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
});
if (!response.ok) {
console.log("User is not authenticated, response not ok");
router.push("/");
}
} catch (error) {
console.error("Error:", error.message);
}
}
};
checkUser();
return null; // Return null to avoid rendering any content
}