我需要检查用户是否已注册。这就是我在文件中所做的_app.tsx:
const MyApp = ({ Component, pageProps }: AppProps) => {
// code
}
export async function getInitialProps(ctx:NextPageContext) {
if (!ctx.req) return { props: { } };
const cookie = ctx.req.headers.cookie!;
const response = await fetch(`${process.env.API_URL}/api/auth/auth`, {
headers: { cookie }
})
const data = await response.json();
return {
props: { data }
}
}
export default MyApp;
我通过中间件在服务器上工作,但它不以任何方式响应(console.log(1)):
const authenticated = (fn: any) => async (req: IGetUserAuthInfoRequest, res: NextApiResponse) => {
const { method, cookies } = req;
console.log(1); // не выводится
if (method === "OPTIONS") {
return fn(req, res);
}
try {
const token = cookies.token;
const decoded = verify(token, `${process.env.JWT_KEY}`);
if (!decoded) {
return res.status(500).json({
success: false, message: "Sorry you are not authenticated"
})
}
req.user = decoded;
return await fn(req, res);
} catch (e: any) {
return res.status(500).json({
success: false, message: "Sorry you are not authenticated: " + e.message
})
}
}
export default authenticated;
服务器上的函数本身如下所示:
import authenticated from "../middleware/auth.middleware";
export default authenticated(async function auth(req: IGetUserAuthInfoRequest, res: NextApiResponse) {
const { method } = req;
if (method === "GET") {
try {
const user: any = req.user;
const payload = { email: user.email, id: user.id };
const token = jwt.sign(payload, `${process.env.JWT_KEY}`, { expiresIn: "24h" });
return res.status(200).json({ success: true, token });
} catch (e: any) {
console.log(e);
res.status(500).json({ success: false, message: `Server error, try again: ${e.message}` });
}
} else {
res.status(405).json({
message: "We only supported GET"
});
}
});
当我登录时,我将所有内容保存在Cookie:
res.setHeader("Set-Cookie", cookie.serialize("token", token, {
httpOnly: true,
secure: process.env.NODE_ENV !== "development",
sameSite: "strict",
maxAge: 3600,
path: "/"
}));
简而言之,问题是服务器没有返回任何东西,甚至console.log(1)
我联系了服务器
React.useEffect(),一切正常:auth:W
_app写道: