【问题标题】:Organizing express.Router with a class?用类组织 express.Router?
【发布时间】:2019-07-14 09:50:04
【问题描述】:

我正在尝试使用 Express 路由器和 Typescript 中的类来组织我的路线。这是我到目前为止所尝试的。 index.ts 文件应该引用 notes.ts 文件中的 Notes 类,该文件通过私有方法公开端点。

例如,我有一个文件index.ts

import * as express from "express";
import rootRoutes from "./root";
import { Notes } from "./notes";
import accountRoutes from "./account";

const router: express.Router = express.Router();
router.use("/", rootRoutes);
router.use("/account", accountRoutes);
router.use("/notes", Notes.routes);

export = router;

还有另一个文件notes.ts:

import express, { Router, Request, Response, NextFunction } from "express";
const router: express.Router = express.Router();

export class Notes {

    constructor() {
        this.routes();
    }

    private routes(): void {
        //Get notes
        router
            .route("/")
            .get((req: Request, res: Response, next: NextFunction) => {
                res.send("notes");
            });
    }
}

我在这里错过了什么?

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

    你正在调用一个私有方法router.use("/notes", Notes.routes);

    要像您一样使用它,首先您必须实例化该类或将方法设为静态。

    将类实例状态与路由器状态混合可能会很棘手,请尽量使其不受任何实例状态的影响。

    另外,我建议您将该实现简化为如下所示:

    export class Notes {
        static handler(req: Request, res: Response): void {
           res.send('Hello from A!')
        }
    }
    
    
    app.get('/', Notes.handler);
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 2013-08-05
      • 2020-12-02
      • 1970-01-01
      • 2020-11-28
      • 2011-01-12
      相关资源
      最近更新 更多