Next.js 为什么 cookie 没有通过 getServerSideProps 发送到服务器?

Why are cookies not sent to the server via getServerSideProps in Next.js?

Cookies不是通过getServerSideProps发送到服务器的,这里是前端的代码:

export async function getServerSideProps() {
  const res = await axios.get("http://localhost:5000/api/auth", {withCredentials: true});
  const data = await res.data;
  return { props: { data } }
}

在服务器上,我有一个检查访问 JWT 令牌的策略。

export class JwtStrategy extends PassportStrategy(Strategy, "jwt") {
    constructor() {
        super({
            ignoreExpiration: false,
            secretOrKey: "secret",
            jwtFromRequest: ExtractJwt.fromExtractors([
                (request: Request) => {
                    console.log(request.cookies) // [Object: null prototype] {}
                    let data = request.cookies['access'];
                    return data;
                }
            ]),
        });
    }

    async validate(payload: any){
        return payload;
    }
}

也就是说,当我通过 getServerSideProps 发送请求时,cookie 不会到达服务器,但如果我发送请求,例如通过 useEffect,则 cookie 会正常到达。

那是因为 getServerSideProps 中的请求不会 运行 在浏览器中 - 每个请求都会自动发送 cookie - 但实际上是在服务器上执行的,在 Node.js环境。

这意味着您需要 axios 请求发送它们。

export async function getServerSideProps({ req }) {
    const res = await axios.get("http://localhost:5000/api/auth", {
        withCredentials: true,
        headers: {
            Cookie: req.headers.cookie
        }
    });
    const data = await res.data;
    return { props: { data } }
}

相同的原则适用于从API路由到外部API的请求,也需要显式传递cookie。

export default function handler(req, res) {
    const res = await axios.get("http://localhost:5000/api/auth", {
        withCredentials: true,
        headers: {
            Cookie: req.headers.cookie
        }
    });
    const data = await res.data;
    res.status(200).json(data)
}