我正在尝试在我的
express
后端创建注销路由。基本上,当用户注销时,他们的 JWT 令牌会保存在 blacklist
Mongo 数据库中,因此他们无法使用相同的令牌再次登录。
问题是我的
blacklist
模式出现打字稿错误:
Type '{ 类型:StringConstructor;必需:真实; }' 不可分配给类型 'string'.ts(2322) (属性)标记:{ 类型:字符串构造函数; 必需:真实; }
我的
blacklist
Mongo 架构:
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import mongoose, { Schema } from "mongoose";
import { BlacklistMongo } from "../types/blacklist";
const blacklistSchema: Schema<BlacklistMongo> = new mongoose.Schema({
token: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, { timestamps: true });
blacklistSchema.set('toJSON', {
transform: (_document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
}
});
export default mongoose.model<BlacklistMongo>('Blacklist', blacklistSchema);
logoutRouter
:
import express from 'express';
import middleware from '../utils/middleware';
import { Response } from 'express';
import { BlacklistMongo } from '../types/blacklist';
import blacklist from '../models/blacklist';
const logoutRouter = express.Router();
logoutRouter.post('/', async (request, response, next) => {
try {
const token: string | null = middleware.getTokenFrom(request);
if (!token) {
throw new Error('Token not found');
}
const tokenid: Promise<string | Response> = middleware.tokenValidator(request, response);
if (tokenid instanceof Response) {
return tokenid;
}
const addedToken: BlacklistMongo = new blacklist({
token: token
});
await addedToken.save();
response.status(200).json('You have been successfully logged out!');
} catch (exception) {
next (exception);
}
});
export default logoutRouter;
实际上,我决定删除架构并再次重写代码,删除用户,并且由于某种原因它起作用了。
类型:
import { Document } from "mongoose";
export interface BlacklistMongo extends Document {
token: string;
}
export interface BlacklistType {
token: string;
}
黑名单型号:
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import mongoose, { Schema } from "mongoose";
import { BlacklistMongo } from "../types/blacklist";
const blacklistSchema: Schema<BlacklistMongo> = new mongoose.Schema({
token: { type: String, required: true }
});
blacklistSchema.set('toJSON', {
transform: (_document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
}
});
export default mongoose.model<BlacklistMongo>('Blacklist', blacklistSchema);