简体   繁体   中英

Getting the response from axios passed on Session storage (user authtoke) with React works fine only once and never again

I am learning how to create react Apps and got myself in very deep hole that I cannot leave by myself, so I've decided to reach out for help of the most spectacular people out there that are you! :)

When I run my App for the first time everything goes well until I logout and I try to log back in again and my session storage is not updated with the function.

It happens that after I run yarn add axios it works just fine and if I logout I have to run the command 'yarn add axios' and restart my server to get my login working for once more. It is a pain in the neck.

I hope someone out there with fresh eyes can help me out on this. Thank you so much!

import React, { Component } from "react";
import { Router } from "@reach/router";

import NavBar from "./components/navbar/NavBar";
import { SERVER_URL } from "./config.js";
import axios from "axios";

import "./index.css"

export default class App extends Component {
  constructor(props) {
    super(props);
    let auth = JSON.parse(sessionStorage.getItem("auth"));
    this.state = {
      isLoggedIn: !!auth ? true : false,
      currentUser: null
    };
  }

  componentDidMount() {
    this.getUser();
  }

  getUser() {
    let auth = JSON.parse(sessionStorage.getItem("auth"));
    if (!auth) return;

    axios
      .get(`${SERVER_URL}/api/users/${auth.userId}`, {
        headers: { Authorization: `Bearer ${auth.token}` }
      })
      .then(response => {
        this.setState({
          currentUser: response.data,
          isLoggedIn: true
        });
      });
  }

  handleLogin(email, password) {
    axios
      .post(`${SERVER_URL}/api/auth/get_token`, {
        email: email,
        password: password
      })
      .then(response => {
        sessionStorage.setItem('auth', JSON.stringify(response.data));
        this.getUser();
      })
      .catch(err => {
        alert(err)
      });
  }

  handleLogout() {
    sessionStorage.setItem("auth", null);
    this.setState({ currentUser: null, isLoggedIn: false });
  }

  render() {
    const userProps = {
      isLoggedIn: this.state.isLoggedIn,
      currentUser: this.state.currentUser,
      logout: () => this.handleLogout(),
      login: (email, pass) => this.handleLogin(email, pass)
    };

    return (
      <>
        <NavBar user={userProps}></NavBar>

      </>
    );
  }
}

This is my Rails backend that seems to be working well:

def get_by_id

      user = User.find(params[:user_id])

        if user
            render json: { id: user.id, name: user.name, email: user.email},
                   status: :ok
        else
            render json: { errors: 'User not found' }, status: :not_found
        end
  end

  def get_token

        user = User.find_by_email(params[:email])

        if !user
            render json: { error: 'unauthorized' }, status: :unauthorized
            return
        end

        if !user.authenticate( params[:password] )
            render json: { error: 'unauthorized' }, status: :unauthorized
            return
        end

        token = jwt_encode({user_id: user.id}, 24.hours.from_now)
        render json: {token: token, exp: 24, username: user.email, userId: user.id},
               status: :ok
        return

  end

The Json file that is returned by the backend looks good to me:


{
    "token": "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJleHAiOjE1NzY3MzcxOTZ9.aK7oLuHZ1r-aI8t-QVT0kV-i5mTYb3B9NiacWJJD9aU",
    "exp": 24,
    "username": "a@a.com",
    "userId": 1
}

But even after getting an apparently good response from the backend I still cannot update my sessionStorage more than once =/


Are you getting any error? Or are you getting the response from get_token api when you retried login?

You don't need to yarn add axios everytime. If you think axios is the problem then you can use fetch api for http requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM