【发布时间】:2020-03-08 20:07:51
【问题描述】:
您好,我正在使用 localStorage 从我的 api 中保存我的 jwt 令牌 但即使我关闭节点服务器等,它也会保存我的令牌。 我需要做一个登录检查
这是我的服务器路由
app.route('/login')
.post(async (req,res)=>{
try {
const response = await usersControllers.signin(req.body);
const login = response.login;
console.log(login);
if(login.id && login.isValid){
const payload = {id: login.id};
res.json({
token: jwt.sign({data:payload}, app.config.jwt.secret,{expiresIn: '60'}),
response
});
}else{
console.log('entrou here');
res.sendStatus(HttpStatus.UNAUTHORIZED);
}
} catch (error) {
console.log('entrou here');
console.error(error.message);
res.sendStatus(HttpStatus.UNAUTHORIZED);
}
})
然后在我的前端做出反应
我的登录中有这个:
import React, { Component } from 'react';
import {Form,FormGroup, Label, Input, Button, Alert} from 'reactstrap';
import Header from '../../components/header';
export default class Login extends Component {
constructor(props) {
super(props)
console.log(this.props);
this.state = {
message: this.props.location.state?this.props.location.state.message: '',
};
}
signIn = () => {
const data = {login:this.login,password:this.password};
const requestInfo = {
method:'POST',
body: JSON.stringify({data}),
headers: new Headers({
'Content-Type': 'application/json'
}),
};
fetch('http://localhost:9000/login', requestInfo)
.then(response => {
if(response.ok){
return response.json();
}
throw new Error("Login Invalido..")
})
.then(token => {
localStorage.setItem('token', token.token);
this.props.history.push("/users");
return;
})
.catch(e => {
this.setState({message: e.message})
});
}
render(){
return(
<div className="col-md-6">
<Header title="ReactJS Login"/>
<hr className="my-3"/>
{
this.state.message !== ''? (
<Alert color="danger" className ="text-center"> {this.state.message}</Alert>
) : ''
}
<Form>
<FormGroup>
<Label for="login">Login</Label>
<Input type="text" id="login" onChange={e => this.login = e.target.value } placeholder="Informe seu login" />
</FormGroup>
<FormGroup>
<Label for="password">Senha</Label>
<Input type="text" id="password" onChange={e => this.password = e.target.value } placeholder="Informe sua senha"/>
</FormGroup>
<Button color="primary" onClick={this.signIn}> Entrar </Button>
</Form>
</div>
);
}
}
在这里我将我的 jwt 设置在 localstorage 中:
.then(token => {
localStorage.setItem('token', token.token);
this.props.history.push("/users");
return;
})
在我的另一个 js 文件中 我对 jwt 的认证
const isAuth = () => {
console.log(localStorage.getItem('token'));
if(localStorage.getItem('token') !== null) {
console.log("entrou aq2");
return true;
}
return false;
};
在 console.log(localStorage.getItem('token'));有价值!==所有时间
即使没有使用我的 api 登录
【问题讨论】:
-
localStorage中的值永远不会过期。也许您可以考虑改用sessionStorage? -
@dev_junwen 如何创建 sessionStorage?
-
我在使用重定向将未经身份验证的用户移动到家时遇到问题,但它不起作用。
-
还有其他“更正确”的选项还是 sessionStorage 是最好的?
标签: node.js reactjs local-storage