首页 > 解决方案 > 在服务器上访问 Next.js 客户端状态

问题描述

我正在尝试使用该getServerSideProps函数在我的 Next.js 应用程序中获取动态数据。该请求必须包含一个存储在客户端的令牌,以在后端对用户进行身份验证。

我尝试了以下方法:

export async function getServerSideProps(context) {
  const token = window.localStorage.getItem('token')
  const data = await axios.get("/data", { headers: { Authorization: `Bearer ${token}` }});
  return { props: { data } };
}

但是我明白ReferenceError : window is not defined了,这是有道理的,因为请求是在服务器上发出的,而window对象不存在那里(它只存在于客户端上)。

我可以getServerSideProps在服务器上访问客户端状态或存储下一个状态吗?如果没有,看起来唯一的方法就是在客户端发出请求。

标签: reactjsreduxnext.jsserver-side-rendering

解决方案


改用 cookie。因为getServersideProps发生在服务端渲染,所以window或者localStorage不能访问。使用 cookies 和 js-cookie 库来设置和获取令牌。


推荐阅读