Nextjs 不能在 getStaticProps 或 getServerSideProps 中使用导入变量

时间:2021-07-06 18:03:28

标签: next.js

这是我第一次发布问题。你好,我是 nextjs 的新手,我正在将它与 django drf 和 postgres 一起使用。问题是我不能使用'js-cookie',其中我在 getStaticProps 中的 profile.js 文件顶部导入,也不能像这样 getServerSideProps:

我的导入:

import Cookies from 'js-cookie'
import jwt_decode from 'jwt-decode'

我在 getStaticProps/getServerSideProps 中的用例,当我 console.log(token) 返回 undefined 时: enter image description here

我的用例不在 getStaticProps 或 getServerSideProps 中,但它可以工作并且可以正确读取令牌:

enter image description here

此外,如果我直接粘贴 jwt 也可以使用,但它不是动态的,我不希望这样:

enter image description here

这些是错误,当我执行 console.log(token) 时它返回 undefined: enter image description here enter image description here

2 个答案:

答案 0 :(得分:0)

js-cookie 是一个基于浏览器的解决方案,它只适用于浏览器环境。

getStaticPropsgetServerSideProps 只在服务器上运行,它们没有 document.cookie 或类似的东西。

您需要使用一些能够接受 cookie 字符串作为参数的库。您可以从 req.headers.cookie 获取 cookie 字符串,但只能在 getServerSideProps 中使用,您不能使用 getStaticProps,因为它应该生成静态页面并且它没有 request 对象.

例如,您可以使用 https://github.com/maticzav/nookies,它是专门为 Next.js 制作的

答案 1 :(得分:0)

您创建一个 cookie 来存储与您发出请求的服务器相关的数据。 merge(df1, df2, by = 0, all = TRUE, suffixes = c('', '.1'), sort = FALSE) 会将 cookie 以一个名称保存到浏览器中。因此,当您的浏览器向同一服务器发出另一个请求时,它会自动将 cookie 附加到 js-cookie 对象。 req 接收 getServerSideProps() 对象。

context