Node.js 带有React的登录令牌

Node.js 带有React的登录令牌,node.js,reactjs,authentication,Node.js,Reactjs,Authentication,我正在使用React连接登录功能,并且遇到了用户会话令牌的问题 问题: 我能够成功登录并创建用户会话令牌(通过控制台验证),但是,一旦我在成功登录后刷新页面,它会将我重定向回登录页面,就像我没有令牌一样 为什么会出现这种代币问题?这是一个象征性的问题吗 我已经对反应进行了编码,所以如果!令牌,然后直接登录表单,如果有令牌,则重定向到占位符('帐户') 您需要在获得令牌后将其保存到cookie中。 并在页面刷新后从cookie中获取令牌。请同时显示存储代码。您如何存储令牌?@niks将令牌添加到存

我正在使用React连接登录功能,并且遇到了用户会话令牌的问题

问题: 我能够成功登录并创建用户会话令牌(通过控制台验证),但是,一旦我在成功登录后刷新页面,它会将我重定向回登录页面,就像我没有令牌一样

为什么会出现这种代币问题?这是一个象征性的问题吗

我已经对反应进行了编码,所以如果!令牌,然后直接登录表单,如果有令牌,则重定向到占位符('帐户')


您需要在获得令牌后将其保存到cookie中。
并在页面刷新后从cookie中获取令牌。

请同时显示存储代码。您如何存储令牌?@niks将令牌添加到存储中question@Udit将令牌存储添加到question@revup88您好,这方面的问题是componentDidMount运行并且不等待getFromStorage函数完成。如果您可以尝试使componentDidMount异步并等待getFromStorage,请尝试此方法并让我知道。示例:
async componentDidMount(){const obj=wait getFromStorage('OI_Login')///代码的其余部分}
import React, { Component } from 'react';
import { Form, Container, Button, Spinner } from 'react-bootstrap'
import { getFromStorage, setInStorage } from '../utils/storage'

export default class LoginUser extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true,
      token: '',
      logInError: '',
      logInEmail: '',
      logInPassword: '',
    }

    this.onChangeLogInEmail = this.onChangeLogInEmail.bind(this);
    this.onChangeLogInPassword = this.onChangeLogInPassword.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.logout = this.logout.bind(this);

  }

  componentDidMount() {
    const obj = getFromStorage('OI_Login')
    if (obj && obj.token) {
      const { token } = obj
      // verify token
      fetch('http://localhost:5001/users/verify?token' + token)
        .then(res => res.json())
        .then(json => {
          if (json.success) {
            this.setState({
              token,
              isLoading: false
            })
          } else {
            this.setState({
              isLoading: false
            })
          }
        })

    } else {
      this.setState({
        isLoading: false,
      })

    }
  }

  // ON CHANGE
  onChangeLogInEmail(e) {
    this.setState({
      logInEmail: e.target.value
    })
  }

  onChangeLogInPassword(e) {
    this.setState({
      logInPassword: e.target.value
    })
  }

  logout(e) {
    e.preventDefault()
    this.setState({
      isLoading: true,
    })
    const obj = getFromStorage('OI_Login')
    if (obj && obj.token) {
      const { token } = obj
      // verify token
      fetch('http://localhost:5001/users/logout?token' + token)
        .then(res => res.json())
        .then(json => {
          if (json.success) {
            this.setState({
              token: '',
              isLoading: false,
              logInError: ''
            })
          } else {
            this.setState({
              isLoading: false
            })
          }
        })

    } else {
      this.setState({
        isLoading: false,
      })
    }
  }

  onSubmit(e) {
    e.preventDefault()
    const {
      logInEmail,
      logInPassword
    } = this.state

    this.setState({
      isLoading: true,
    })

    //post request to backend
    fetch('http://localhost:5001/users/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: logInEmail,
        password: logInPassword
      }),
    }).then(res => res.json())
      .then(json => {
        if (json.success) {
          setInStorage('OI_Login', { token: json.token })
          this.setState({
            logInError: json.message,
            isLoading: false,
            logInEmail: '',
            logInPassword: '',
            token: json.token
          })
        } else {
          this.setState({
            logInError: json.message,
            isLoading: false
          })
        }
      })

  }

  render() {
    const {
      isLoading,
      token,
      logInError,
      logInEmail,
      logInPassword,
    } = this.state

    if (isLoading) {
      return (
        <>
          <div className="justify-content-center">
            <Spinner animation="border" />
          </div>
        </>
      )
    }

    if (!token) {
      return (
        <>
          <Container>
            <h3>Log In</h3>
            <Form>
              <Form.Group>
                <Form.Label>Email</Form.Label>
                <Form.Control
                  required
                  type="email"
                  id="email"
                  value={logInEmail}
                  onChange={this.onChangeLogInEmail}
                />
              </Form.Group>
              <Form.Group>
                <Form.Label>Password</Form.Label>
                <Form.Control
                  required
                  type="password"
                  id="password"
                  value={logInPassword}
                  onChange={this.onChangeLogInPassword}
                />
              </Form.Group>
              <div>
                {
                  (logInError) ? (
                    <p>{logInError}</p>
                  ) : (null)
                }
              </div>
              <Form.Group>
                <Button variant="btn btn-primary" onClick={this.onSubmit} type="submit">Log In</Button>
              </Form.Group>
            </Form>
            <a href='/register'>Register</a>
          </Container>
        </>
      )
    }

      return (
        <>
          <p>Account</p>
          <Button variant="danger" onClick={this.logout}>Log Out</Button>
        </>
      )

  }

}
export function getFromStorage(key) {
  if (!key) {
    return null
  }

  try {
    const valueStr = localStorage.getItem(key)
    if (valueStr) {
      return JSON.parse(valueStr)
    }
    return null
  } catch (err) {
    return null
  }
}

export function setInStorage(key, obj) {
  if (!key) {
    console.error('Error: Key is missing')
  }

  try {
    localStorage.setItem(key, JSON.stringify(obj))
  } catch (err) {
    console.error(err)
  }

}