【发布时间】:2022-07-11 19:35:17
【问题描述】:
我目前正在使用 Iron-session 和 next.js 进行一个项目。点击 Link 标签不会失去我的用户。但是,如果我刷新用户变得未定义。 Cookie 已设置并且不会在刷新时被删除。不知道怎么回事。
这是我的 login.ts 代码:
export default withIronSessionApiRoute(loginRoute, sessionOptions);
async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
try {
const {
data: {tcId, admin, userName},
} = await axios('http://localhost:8080/user/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(req.body),
});
const user = {tcId: tcId, userName: userName, admin: admin} as User;
req.session.user = user;
await req.session.save();
res.json(user);
} catch (error) {
res.status(500).json({message: (error as Error).message})
}}
这是我的 session.ts 代码:
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import type { IronSessionOptions } from 'iron-session'
import type { User } from '../pages/api/user'
export const sessionOptions: IronSessionOptions = {
password: process.env.SECRET_COOKIE_PASSWORD as string,
cookieName: 'eys-cookie',
// secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
};
// This is where we specify the typings of req.session.*
declare module 'iron-session' {
interface IronSessionData {
user?: User
}
}
正如我之前所说。我不会失去我的用户。在使用下一个 Link 标记进行路由时。 刷新导致失去我的用户。其他标签也无法访问我的用户。
如果需要,我可以显示更多代码。但我认为问题就在这里。
-
你如何检查用户是否通过身份验证?