【发布时间】:2019-05-30 20:55:47
【问题描述】:
我正在学习 Next.JS 和 React,想知道是否可以从存储 JWT 的 cookie 中获取用户详细信息。
我已设法将 JWT 设置为 cookie,并且可以成功记录它,还设法对其进行解码,但找不到任何关于如何从中获取用户名、ID 等的信息。到目前为止,这是我所拥有的:
import React from "react";
import App from "../components/App.js";
import cookie from "react-cookies";
import jwt_decode from "jwt-decode";
export default class Dashboard extends React.Component {
static async getInitialProps() {
const token = cookie.load("jwt");
return { token };
}
constructor(props) {
super(props);
this.state = props.token;
}
render() {
const current_user = jwt_decode(this.props.token, { header: true });
return (
<App>
<p>Username: {current_user.username}</p>
</App>
);
}
}
理想情况下,我希望能够将 cookie 值设置为用户变量并从中提取属性,例如current_user.username。除非我完全错了并且错过了一些非常重要的事情!任何帮助将不胜感激!
【问题讨论】:
-
目前的行为是什么?
标签: reactjs cookies jwt next.js