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

IT技术 node.js reactjs jwt next.js nestjs
2021-04-20 07:14:57

Cookie 不会通过 发送到服务器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;
    }
}

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

1个回答

这是因为内部的请求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 } }
}
谢了哥们。这有助于解决基于 nextjs + lumen api 的应用程序的问题。
2021-06-14 07:14:57