reactjs - 如何使用 Nest.js 和 JWT 使客户端用户在页面刷新和导航中保持不变
问题描述
我目前正在使用 Nest 和 React 处理一个较大项目的一小部分。已经使用 JWT 完成了服务器端身份验证。我们已经构建了登录功能。请参见下面的代码片段:
import * as React from 'react';
import Button from '@material-ui/core/Button';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import { useHistory } from 'react-router-dom';
import jwt from 'jsonwebtoken';
import type { Theme } from '@material-ui/core/styles';
import EmailInput from './EmailInput';
import FacebookAuthBtn from './FacebookAuthBtn';
import GoogleAuthBtn from './GoogleAuthBtn';
import PasswordInput from './PasswordInput';
import StyledLink from './StyledLink';
import TextDivider from './TextDivider';
import { UserContext } from './providers';
...
interface UserLoginData {
email: string;
password: string;
}
const initialFormData: UserLoginData = {
email: '',
password: '',
};
function Login() {
const classes = useStyles();
const history = useHistory();
const [, setUser] = React.useContext(UserContext);
const [ formData, setFormData ] = React.useState(initialFormData);
const handleChange = (evt: React.ChangeEvent<HTMLInputElement>): void => {
const { name, value }: { name: string; value: string } = evt.target;
setFormData((fData) => ({
...fData,
[name]: value,
}));
};
const handleSubmit = async (evt: React.FormEvent) => {
evt.preventDefault();
try {
const res = await fetch('http://localhost:3001/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
// credentials: "include",
body: JSON.stringify(formData),
});
const response = await res.json();
// TODO replace placeholder with .env var
const user = jwt.verify(response.access_token, 'placeholder');
setUser(user);
history.push('/');
} catch (err) {
// Handle error
}
};
return (...)
所以建立handleSubmit函数,在我得到JSON我的响应之后,我想,我需要做一些身份验证?我的目标是在客户端编写代码,让用户在页面刷新和导航中保持不变。
任何提示或建议表示赞赏!
解决方案
推荐阅读
- firebase - Can I merge data when sending put request to firebase realtime database using axios?
- github - 通过浏览器删除 Github 上的 Commit
- php - PHP按值分组关联数组的键
- list - 用于从列表中删除元素的书签
- javascript - POST 请求 - 不适用于 Node 和 Express
- android - 无法确定任务 ':app:lintVitalRelease' 的依赖关系
- android - Android Studio 作为 Flutter Project 运行 Android (Java) 项目
- flutter - 如何将本机 macOS 可执行文件与颤振应用程序捆绑在一起?
- sql-server - Azure VM SQL Server 使用来自另一个 Azure VM ASP.NET 应用程序的 Windows 身份验证
- javascript - Nodejs,Webpack4