为什么 cookie 不通过 Next.js 中的 getServerSideProps 发送到服务器?

Ово*_*чоы 23 node.js jwt reactjs next.js nestjs

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 } }
}
Run Code Online (Sandbox Code Playgroud)

在服务器上,我有一个检查访问 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

jul*_*ves 49

这是因为里面的请求getServerSideProps并不在浏览器中运行(每个请求都会自动发送 cookie),而是实际上在 Node.js 环境中的服务器上执行。

这意味着您需要将cookie 显式传递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 } }
}
Run Code Online (Sandbox Code Playgroud)

同样的原则适用于从 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)
}
Run Code Online (Sandbox Code Playgroud)