由于JWT令牌的生命周期为15秒,因此我想在此之后清除Cookie.但我不知道该怎么做才好.它需要在服务器端完成,还是可以在客户端完成?Code with description below

使用mongoose,我创建了一个用户模型,并向其中添加了一个JWT令牌.

const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');

const userSchema = new mongoose.Schema({
  email: { type: String, required: true },
  password: { type: String, required: true },
});

userSchema.methods.generateAuthToken = function() {
  const token = jwt.sign({ _id: this._id }, process.env.JWTPRIVATEKEY, {expiresIn: "15s"})
  return token
};

const User = mongoose.model('users', userSchema);

module.exports = { User }

const router = require('express').Router();
const { User } = require('../models/User');

router.post('/', async (req, res) => {
  try {
    const user = await User.findOne({ email: req.body.email });

    const token = user.generateAuthToken();
    res.status(200).send({ data: token, message: "Logging in is successful" });
  } catch (error) {
    console.log(error);
    res.status(500).send({ message: 'Internal Server Error' })
  }
});

data: token这是智威汤逊发行的密钥.回想一下,这是在创建用户时创建的JWT令牌.请参阅前面的代码


接下来是一个简单的表单,在该表单中我发出请求并接收一个令牌作为响应,我将其存储在Cookie中

import { Cookies } from "react-cookie";
    
const cookies = new Cookies();
    
const handleChange = ({ currentTarget: input }) => {
  setData({ ...data, [input.name]: input.value });
};
    
const handleSubmit = async (event) => {
  event.preventDefault();
   try {
     const url = "http://localhost:8080/api/auth";
     const { data: res } = await axios.post(url, data);
     cookies.set('token', res.data);
   } catch (error) {}
       
<form onSubmit={handleSubmit}>
  <input type="email" name={"email"} value={data.email} onChange={handleChange} required placeholder={"Email"} />
  <input type="password" name={"password"} value={data.password} onChange={handleChange} required placeholder={"Password"} />
  <button type="submit">Login</button>
</form>

And this is the JWT token I mentioned above. enter image description here

推荐答案

在使用jwt.verify()运行任何需要JWT令牌的请求之前,您将判断客户端上的JWT令牌是否已过期.

jwt.verify(token, 'shhhhh', function(err, decoded) {
  if (err) {
    /*
      err = {
        name: 'TokenExpiredError',
        message: 'jwt expired',
        expiredAt: 1408621000
      }
    */
  }
});

if (err)中,您将处理使用户会话无效的操作,例如从他们的cookie中删除过期令牌并将其重定向到您的登录表单.

Node.js相关问答推荐

序列化事务未按预期工作

postgresql层与应用层的序列化

使用参考中断Mongoose模型-Node.js

仅在一次查询中 MongoDB 上最近的一对位置

我的 React + Express 应用程序不断向我的数组添加一个空对象

为什么我的 Node.js 应用程序在登录时无法正确验证密码(使用 Passport-local 和 bcryptjs)?

是否可以在 NodeJS 代码库中的每个函数之前和之后添加 console.log?

如何在Node.js的telegraf.js命令中添加参数?

表达 js 错误处理程序在第一个之后被忽略

我正在try 在公共目录中使用 Express.js 项目部署 Angular 静态构建

无法使用 node 预签名 url 从 React 将图像文件上传到 s3

npm chokidar 触发事件两次

使用 $in 查询时,如何获取 mongoDB 中每个唯一 ID 的 n 个文档?

如何正确使用 package.json 中的关键字属性?

npm 不会安装 express 吗?

Nodejs 随机免费 tcp 端口

Mongoose - 保存字符串数组

路由后的 Node Express 4 中间件

react-native run-android 无法识别

用于轻松部署和更新的 Node.js 设置