Express.js.路由级中间件没有被调用



我有一个API与Express.js和TypeScript。它工作得很好,除了中间件没有被调用——路由请求成功地传递给处理程序,但中间件根本没有参与。

路由是这样定义的

class TagsRoute implements Routes {
public path = '/tags';
public router = Router();
public tagsController = new TagsController();
constructor() {
this.initializeRoutes();
}
private initializeRoutes() {
this.router.get(`${this.path}`, this.tagsController.getTagPosts);
this.router.get(`${this.path}/read`, this.tagsController.getTags);
this.router.post(`${this.path}`, authMiddleware, this.tagsController.addTag);
this.router.delete(`${this.path}`, authMiddleware, this.tagsController.deleteTag);
this.router.put(`${this.path}`, authMiddleware, this.tagsController.editTag);
}
}
export default TagsRoute;

中间件是这样定义的:

const authMiddleware = (error: HttpException, req: Request, res: Response, next: NextFunction): void => {
try {
if (
req.headers.authorization &&
req.headers.authorization.split(' ')[0] === 'Bearer'
) {
const token = req.headers.authorization.split(' ')[1];
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
getAuth()
.verifyIdToken(token)
.then((decodedToken) => {
if (!decodedToken || decodedToken.exp < Date.now()) {
res.status(401).json({ message: "Invalid token" });
}
next()
})
.catch((error) => {
res.status(401).json({message: "Invalid token"});
});
}
} catch (error) {
next(error);
}
};
export default authMiddleware;

由于它的第一个参数,authMiddleware是错误处理中间件,它只在之前发生错误并与next(error)传播时被调用。

但是看看authMiddleware的代码,似乎根本不需要error参数。所以你应该省略它:

const authMiddleware = (req: Request, res: Response, next: NextFunction): void => {
...
};

最新更新