如何在 Next.js 的 `getServerSideProps` 方法中使用 cookie? [英] How to use cookie inside `getServerSideProps` method in Next.js?

查看:24
本文介绍了如何在 Next.js 的 `getServerSideProps` 方法中使用 cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在端点上发送当前语言.但是从 Cookie 获取语言会在 getServerSideProps 中返回 undefined.

I have to send current language on endpoint. But getting language from Cookie returns undefined inside 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;

getServerSideProps 中获取 cookie 的正确方法是什么?

What is the proper way to get cookie inside getServerSideProps?

推荐答案

你可以从getServerSideProps里面的req.headers获取cookies:

You can get the cookies from the req.headers inside getServerSideProps:

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

然后您可以使用 cookie npm 包来解析它们:

You could then use the cookie npm package to parse them:

import * as cookie from 'cookie'

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

这篇关于如何在 Next.js 的 `getServerSideProps` 方法中使用 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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