簡體   English   中英

用班級組織express.Router嗎?

[英]Organizing express.Router with a class?

我正在嘗試使用Express路由器和Typescript中的類來組織路由。 到目前為止,這是我嘗試過的。 index.ts文件應該引用在注釋類notes.ts暴露經由專用方法的端點文件。

因此,例如,我有一個文件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");
            });
    }
}

我在這里想念什么?

您正在調用私有方法router.use("/notes", Notes.routes);

要像您一樣使用它,首先必須實例化該類或使該方法靜態。

將類實例狀態與路由器狀態混合在一起可能會比較棘手,請嘗試使其脫離任何實例狀態。

我也建議您將實現簡化為以下形式:

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


app.get('/', Notes.handler);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM