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

时间:2020-09-12 12:33:48

标签: next.js i18next

我必须在端点上发送当前语言。但是从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;

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

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以从req.headers内的getServerSideProps获取cookie:

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

然后您可以使用cookies npm程序包来解析它们:

import * as cookie from 'cookie'

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

答案 1 :(得分:0)

您可以将import math, random, csv import matplotlib.pyplot as plt import numpy as np headers = [] data = [] def getdata(fn): with open(fn) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') line_count = 0 for row in csv_reader: if line_count == 0: headers = row line_count += 1 else: data.append(row) line_count += 1 print(f'Processed {line_count} lines.') print(headers) print(data) def main(): getdata('intlrankings.csv') main() 函数与cookie软件包一起使用

parseCookies

然后像这样获得访问权限。

import cookie from "cookie"

function parseCookies(req){
    return cookie.parse(req ? req.headers.cookie || "" : document.cookie);
}