如何在 Next.js 中的 `getServerSideProps` 方法中使用 cookie?

2024-01-31

我必须在端点上发送当前语言。但是从 Cookie 获取语言返回内部未定义getServerSideProps.

export async function getServerSideProps(context) {
    const lang = await Cookie.get('next-i18next')
    const res = await fetch(`endpoint/${lang}`)
    const data = await res.json()

    return {
        props: { data },
    }
}

export default Index;

将 cookie 放入其中的正确方法是什么getServerSideProps?


您可以从以下位置获取 cookiereq.headers inside getServerSideProps:

export async function getServerSideProps(context) {
  const cookies = context.req.headers.cookie;
  return {
    props: {},
  };
}

然后您可以使用cookie https://www.npmjs.com/package/cookienpm 包来解析它们:

import * as cookie from 'cookie'

export async function getServerSideProps(context) {
  const parsedCookies = cookie.parse(context.req.headers.cookie);
  return { props: {} }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Next.js 中的 `getServerSideProps` 方法中使用 cookie? 的相关文章

随机推荐