首页 > 解决方案 > React.js 在 localStore 中未定义的值

问题描述

我正在尝试使用 Spring Boot API 生成的 JWT 在我的 React 应用程序中对用户进行身份验证。我在获取用户信息时遇到问题。它返回 undefined
在 axios.post 调用后/login我收到带有授权标头的响应。然后我将此令牌存储在localStorage中,设置后 axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');我调用axios.get /user,它返回分配给授权令牌的用户名作为响应,我再次将响应存储在localStorage中。接下来,我调用 axios.get /user/{username}来获取 usersData,如 id、名字、姓氏等。

authService.js

import axios from 'axios';
import { BASE_API_URL } from '../constants/baseURL';

export function login(username, password) {
  axios.post(BASE_API_URL + 'login', { username, password }).then((res) => {
    if (res.data != null) {
      localStorage.setItem('token', res.headers.authorization);
      axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
      getCurentUsername();
      getCurentUserId();
    }
  });
}

export function getCurentUsername() {
  axios.get(BASE_API_URL + 'user').then((res) => {
    if (res.data != null) {
      localStorage.setItem('username', res.data);
    }
  });
}

export function getCurentUserId() {
  axios.get(BASE_API_URL + 'user/' + localStorage.getItem('username')).then((res) => {
    localStorage.setItem('curentUser', res.data.idUsers);
  });
}

export function logout() {
  localStorage.removeItem('token');
  localStorage.removeItem('username');
  localStorage.removeItem('curentUser');
  delete axios.defaults.headers.common['Authorization'];
}

登录.js

import React, { Component } from 'react';
import { Button, Card, Form, Col } from 'react-bootstrap';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSave } from '@fortawesome/free-solid-svg-icons';
import { login } from '../services/authService';

class Login extends Component {
  constructor(props) {
    super(props);
    this.state = this.initialState;
    this.credentialsChange = this.credentialsChange.bind(this);
    this.userLogin = this.userLogin.bind(this);
  }

  initialState = {
    username: '',
    password: '',
  };

  userLogin = (e) => {
    e.preventDefault();
    login(this.state.username, this.state.password);
  };

  credentialsChange = (e) => {
    this.setState({
      [e.target.name]: e.target.value,
    });
  };

  render() {
    const { username, password } = this.state;

    return (
      <Card className={'border border-dark bg-dark text-white'}>
        <Card.Header>Sign In</Card.Header>
        <Form onSubmit={this.userLogin} id="loginFormId">
          <Card.Body>
            <Form.Row>
              <Form.Group as={Col} controlId="formGridCountry">
                <Form.Label>Username</Form.Label>
                <Form.Control
                  required
                  autoComplete="off"
                  type="text"
                  name="username"
                  value={username}
                  onChange={this.credentialsChange}
                  className={'bg-dark text-white'}
                  placeholder="Username"
                />
              </Form.Group>
            </Form.Row>
            <Form.Row>
              <Form.Group as={Col} controlId="formGridZipCode">
                <Form.Label>Password</Form.Label>
                <Form.Control
                  required
                  autoComplete="off"
                  type="text"
                  name="password"
                  value={password}
                  onChange={this.credentialsChange}
                  className={'bg-dark text-white'}
                  placeholder="Password"
                />
              </Form.Group>
            </Form.Row>
          </Card.Body>
          <Card.Footer style={{ textAlign: 'right' }}>
            <Button variant="success" type="submit">
              <FontAwesomeIcon icon={faSave} /> Sign In
            </Button>{' '}
          </Card.Footer>
        </Form>
      </Card>
    );
  }
}

export default Login;

本地存储

如果我再次单击登录按钮,localStore 将更curentUser改为 ID。我做错了什么?像这样存储数据是一种好方法吗?或者也许使用其他库,如 redux 来处理它

标签: reactjsaxios

解决方案


推荐阅读