我只想通过ID获取用户,但是我遇到了一个错误,该错误是在类型字符串上不存在ID,我的代码如下所示:
import asyncHandler from "express-async-handler";
import { NextFunction, Request, Response } from "express";
import User from "../models/User";
import jwt from "jsonwebtoken";
import configs from "../config/config";
const protect = asyncHandler (async (req: Request, res: Response, next: NextFunction) => {
try {
const token = req.cookies.token
if (!token) {
res.status(401)
throw new Error("Not authorized, please login");
}
// Verify Token
const verified = jwt.verify(token, configs.JWT_SECRET)
// Get user id from token
const user = await User.findById(verified.id).select("-password")
if (!user) {
res.status(401)
throw new Error("User was not found")
}
req.user = user
next()
} catch (error) {
}
});
export default protect;