post.controller.ts
class PostController implements Controller {
public path = '/posts';
public router = Router();
private PostService = new PostService();
constructor() {
this.initialiseRoutes();
}
private initialiseRoutes(): void {
this.router.get(
`${this.path}`, this.get);
}
private get = async (
req: Request,
res: Response,
next: NextFunction
): Promise<Response | void> => {
try {
const posts = await this.PostService.get();
res.status(200).json({ posts });
} catch (error:any) {
next(new HttpException(400, error.message));
}
};
}
export default PostController;
post.service.ts
class PostService {
private post = PostModel;
public async get(): Promise<Post[]> {
try {
const posts = await this.post.find();
return posts;
} catch (error) {
throw new Error('Unable to get posts');
}
}
}
export default PostService;
尝试在Nodejs+Express API中使用Mongodb获取博客帖子模型。但收到“无法获取/api/posts”错误。其他请求(如创建帖子和用户CRUD操作)工作正常。
1条答案
按热度按时间oewdyzsn1#
在app.ts文件中,您可能需要初始化数据库、中间件、控制器等等。
然后,只需将应用程序导入到index.ts文件中,并在那里初始化控制器。