【发布时间】:2022-08-18 16:10:39
【问题描述】:
我有一个下一个 JS 应用程序,其登录页面受 requireAuth 组件的保护:
import useAuth from \'../../hooks/useAuth\';
import { useRouter } from \'next/router\';
import { useEffect } from \'react\';
const RequireAuth = ({ children }) => {
const router = useRouter();
const { auth } = useAuth();
// from location is saved in router query
// this is used to redirect to the same page after login
// const from = router.query.from || \'/\'; in login.jsx
useEffect(() => {
if (!auth?.user) {
router.push({
pathname: \'/seller/auth/login\',
query: { from: router.pathname },
});
}
}, [auth?.user]);
return <div>{children}</div>;
};
export default RequireAuth;
require auth 保留用户所在的页面作为查询参数,以便用户可以在登录后被发送到相应的页面。
但是,如果用户从动态参数引用的页面注销:
例如。 http://localhost:3000/seller/panel/products/1
其中 1 指的是 [productId].js 页面
然后登录页面上的 URL 字符串如下:
http://localhost:3000/seller/auth/login?from=%2Fseller%2Fpanel%2Fproducts%2F%5BproductId%5D
在这里,登录后用户未发送到 http://localhost:3000/seller/panel/products/1 并引发错误。
请帮助解决这个问题。
更新:
抛出什么错误:
未处理的运行时错误错误:提供的
href(/seller/panel/products/[productId]) 值缺少查询值 (productId) 被正确插值。阅读更多: https://nextjs.org/docs/messages/href-interpolation-failed登录后如何重定向:
在我的登录组件中:
const router = useRouter(); const from = router.query.from || \'/seller/panel\'; const handleLogin = async (e) => { e.preventDefault(); // regex to test valid email const emailRegex = /^(([^<>()[\\]\\\\.,;:\\s@\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/; const phoneRegex = /^[0-9]{10}$/; if ( !emailRegex.test(values.phoneEmail) && !phoneRegex.test(values.phoneEmail) ) { setResSuccess(false); setResMessage(\'Please enter a valid email or phone number\'); return; } setResMessage(\'\'); setLoading(true); const response = await passwordLogin(values); // console.log(response); setLoading(false); const { success, message, user, roles, stores, accessToken } = response.data; setResSuccess(success); setResMessage(message); if (success) { setAuth({ user, roles, stores, accessToken }); setValues({ phoneEmail: \'\', password: \'\', otp: \'\', }); router.push(from); } };
-
抛出什么错误?
-
你如何重定向到
from? -
在上面的帖子正文中添加了抛出的错误和重定向到 \"from\" 的方法