![](/img/trans.png)
[英]Starting a php session from react with an axios call does not keep the session alive, but doing it with postman works just fine
[英]Getting the response from axios passed on Session storage (user authtoke) with React works fine only once and never again
我正在學習如何創建 React 應用程序並且讓自己陷入了一個我無法獨自離開的深坑,所以我決定向那里最出色的人尋求幫助,那就是你! :)
當我第一次運行我的應用程序時,一切都很順利,直到我注銷並嘗試重新登錄並且我的會話存儲沒有使用該功能更新。
碰巧的是,在我運行 yarn add axios 之后,它工作得很好,如果我注銷,我必須運行命令“yarn add axios”並重新啟動我的服務器以讓我的登錄再次工作。 這是頸部疼痛。
我希望有新眼光的人可以幫助我解決這個問題。 非常感謝!
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>
</>
);
}
}
這是我的 Rails 后端,似乎運行良好:
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
后端返回的 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_token api 獲得響應?
您不需要每次都添加 axios 。 如果您認為 axios 是問題,那么您可以對 http 請求使用 fetch api。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.