首页 > 解决方案 > 如何使用 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我的响应之后,我想,我需要做一些身份验证?我的目标是在客户端编写代码,让用户在页面刷新和导航中保持不变。

任何提示或建议表示赞赏!

标签: reactjsjwtnestjstsx

解决方案


推荐阅读