son*_*dat 3 authentication local-storage next.js
我在 next.js 应用程序中使用 localStorage 令牌。我尝试在 getInitialProps 页面上获取 localStorage 但它返回undefined.
这是一个例子,
Dashboard.getInitialProps = async () => {
const token = localStorage.getItem('auth');
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { 'Authorization': token }
});
const data = await res.json();
return { page: data };
}
Run Code Online (Sandbox Code Playgroud)
对于初始页面加载,
getInitialProps将仅在服务器上运行。然后,当通过组件或使用getInitialProps导航到不同的路线时,将在客户端上运行。文档next/linknext/router
这意味着您将无法localStorage始终访问(仅限客户端)并且必须处理它:
Dashboard.getInitialProps = async ({ req }) => {
let token;
if (req) {
// server
return { page: {} };
} else {
// client
const token = localStorage.getItem("auth");
const res = await fetch(`${process.env.API_URL}/pages/about`, {
headers: { Authorization: token },
});
const data = await res.json();
return { page: data };
}
};
Run Code Online (Sandbox Code Playgroud)
如果您想获取初始页面加载的用户令牌,则必须将令牌存储在其中,cookies而不是localStorage@alejandro 在评论中也提到的位置。
| 归档时间: |
|
| 查看次数: |
24018 次 |
| 最近记录: |