NodeJS 无法获取/API/posts

f45qwnt8  于 2023-03-12  发布在  Node.js
关注(0)|答案(1)|浏览(136)

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操作)工作正常。

oewdyzsn

oewdyzsn1#

app.ts文件中,您可能需要初始化数据库、中间件、控制器等等。

// import all necessary dependencies.

class App {
    public express: Application;
    public port: number;

    constructor(controllers: Controller[], port: number) {
        this.express = express();
        this.port = port;

        this.initialiseDatabaseConnection();
        this.initialiseMiddleware();
        this.initialiseControllers(controllers);
    }

    private initialiseMiddleware(): void {
        this.express.use(cors({ credentials: true, origin: true }));
        this.express.use(express.json());
        this.express.use(express.urlencoded({ extended: false }));
    }

    private initialiseControllers(controllers: Controller[]): void {
        controllers.forEach((controller: Controller) => {
            this.express.use('/api', controller.router);
        });
    }

    private async initialiseDatabaseConnection(): Promise<void> {
        try {
            await mongoose.connect(`${process.env.MONGO_PATH || mongodb://127.0.0.1:27017/test}`);
        } catch (error) {
            throw error;
        }
    }

    public listen(): void {
        this.express.listen(this.port, () => {
                console.log(
                    `App listening on the port ${this.port}`
                );
            });
    }
}

export default App;

然后,只需将应用程序导入到index.ts文件中,并在那里初始化控制器。

// import all necessary dependencies.

const app = new App(
    [
        new PostController(),
    ],
    Number(process.env.PORT || 3000)
);

app.listen();

相关问题