Javascript 使用React从会话存储(用户authtoke)上传递的axios获取响应只能正常工作一次,永远不会再正常工作
我正在学习如何创建react应用程序,让自己陷入了一个无法自拔的深渊,所以我决定寻求最杰出的人的帮助,他们就是你们!:) 当我第一次运行我的应用程序时,一切都很顺利,直到我注销并尝试再次登录,并且我的会话存储没有使用该功能进行更新 在我运行Thread add axios之后,它工作正常,如果我注销,我必须运行命令'Thread add axios',然后重新启动服务器,使我的登录再次工作。 这是一件令人头痛的事 我希望有人有新鲜的眼睛可以帮助我在这方面。 非常感谢您强>Javascript 使用React从会话存储(用户authtoke)上传递的axios获取响应只能正常工作一次,永远不会再正常工作,javascript,ruby-on-rails,reactjs,axios,Javascript,Ruby On Rails,Reactjs,Axios,我正在学习如何创建react应用程序,让自己陷入了一个无法自拔的深渊,所以我决定寻求最杰出的人的帮助,他们就是你们!:) 当我第一次运行我的应用程序时,一切都很顺利,直到我注销并尝试再次登录,并且我的会话存储没有使用该功能进行更新 在我运行Thread add axios之后,它工作正常,如果我注销,我必须运行命令'Thread add axios',然后重新启动服务器,使我的登录再次工作。 这是一件令人头痛的事 我希望有人有新鲜的眼睛可以帮助我在这方面。 非常感谢您 import React,
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>
</>
);
}
}
后端返回的Json文件在我看来很好:
{
"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 =/
你有什么错误吗?或者,当您重试登录时,是否从get_令牌api获得响应
您不需要每次都添加axios。如果您认为axios是问题所在,那么您可以对http请求使用fetch api 谢谢,伙计。那么,我已经按照你的建议和费奇一起去了。到目前为止一切都很好。
{
"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 =/