【发布时间】:2021-11-02 15:29:46
【问题描述】:
我在我的 NextJS 应用程序中使用 with-iron-session 进行身份验证,但是当我在 getServerSideProps() 函数中进行 API 调用时,我无法访问会话 cookie。 API 路由无法获取用于认证的会话 cookie:
会话创建:
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import { withIronSession } from "next-iron-session";
export default function withSession(handler) {
return withIronSession(handler, {
password: process.env.PASSWORD_HASH,
cookieName: "MYCOOKIE",
cookieOptions: {
// the next line allows to use the session in non-https environements like
// Next.js dev mode (http://localhost:3000)
secure: process.env.NODE_ENV === "production",
httpOnly: false,
},
});
}
我的 getServerSideProps 调用:
export const getServerSideProps = withSession(async ({ req, res }) => {
const user = req.session.get("user");
if (!user) {
return {
redirect: {
permanent: false,
destination: "/"
},
props: {}
};
}
// I've replaced 'include' with 'same-origin' but it didn't make a difference
const watchRes = await fetch('/watch',{credentials: 'include'});
const watch = await watchRes.json();
return{
props: {
user,
watch
}
}
}
api 路由:
// I've added await before the (req,res) but that was just guessing at this point
export default withSession((req, res) => {
const user = req.session.get("user");
if(user){
res.send("Good");
}else{
res.status(403).end();
}
}
当我登录并转到我的localhost/api/watch 路由时,它显示“良好”,但当我尝试获取请求时,我得到了 403。
【问题讨论】:
-
请记住,
getServerSideProps在服务器端运行(就像 API 路由一样),因此与其调用内部 API,不如直接在getServerSideProps中使用 API 路由中的逻辑。