reactjs - 在服务器上访问 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
在服务器上访问客户端状态或存储下一个状态吗?如果没有,看起来唯一的方法就是在客户端发出请求。
解决方案
改用 cookie。因为getServersideProps发生在服务端渲染,所以window或者localStorage不能访问。使用 cookies 和 js-cookie 库来设置和获取令牌。
推荐阅读
- java - 如果我使用 == 为什么不安全的单例实例将是真的
- sql - 是否可以在每个案例中添加多个选择语句?
- angular - 获取并显示所有 ngfor 元素各自的当前位置
- windows - 如何修复 JMeterPluginsCMD“缺少插件类型规范”错误
- google-app-engine - 需要帮助正确设置负载均衡器和 googl cloud cdn
- php - magento2 error on Docker: There are no commands defined in the "setup" namespace
- angular - 如何从 firestore DocumentReference 数组字段创建可观察数组
- angular - RouterLink 在路由上附加对象信息
- python-3.x - 使用 RGB 值控制单个数据点 matplotlib
- java - 使用带有 @GeneratedValue 生成的 PrimaryKey 的 jdbctemplate 插入行