Next.js 中为什么没有通过 getServerSideProps 将 cookie 发送到服务器? [英] Why are cookies not sent to the server via getServerSideProps in Next.js?

查看:43
本文介绍了Next.js 中为什么没有通过 getServerSideProps 将 cookie 发送到服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Cookies are not sent to the server via getServerSideProps, here is the code in the front-end:

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 令牌的策略.

On the server I have a strategy that checks the access JWT token.

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 会正常到达.

That is, when I send a request via getServerSideProps cookies do not come to the server, although if I send, for example via useEffect, then cookies come normally.

推荐答案

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

That's because the request inside getServerSideProps doesn't run in the browser - where cookies are automatically sent on every request - but actually gets executed on the server, in a Node.js environment.

这意味着您需要显式传递 cookieaxios 请求以发送它们通过.

This means you need to explicitly pass the cookies to the axios request to send them through.

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 } }
}

这篇关于Next.js 中为什么没有通过 getServerSideProps 将 cookie 发送到服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆