所以我正在koa
和koa-router
我有一个使用 mongo 作为数据库的 api,并且我有一些这样的端点设置:
const router = new Router({ sensitive: false });
router.get(`/author`, controller.getAuthors);
router.get(`/author/:authorId`, controller.getAuthorById);
router.get(`/author/:authorId/books`, controller.getAuthorBooks);
但是,当我运行时GET
,/author/:authorId/books
我在日志中看到了这个错误:
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
传递给 Mongo 以搜索作者的字符串是这样的:
oTKGdrJXo4aUVj9ZC22MMLeA7Z03/books
使用完整koa-router
路径/author/:authorId
(包括/books
.
我该如何防止这种情况?
我知道,如果我首先注册更具体的端点,它会起作用,但我不想担心我注册端点的顺序,这会产生一个非常脆弱的解决方案
编辑
添加实现getAuthorById
:
public async getAuthorById(ctx: Context): Promise<void> {
if (ctx.params.authorId) {
const author = await this.authorService.findById(ctx.params.authorId);
ctx.status = 200;
ctx.body = author;
} else {
ctx.status = 404;
}
}