typescript express app.use在类内部使用时不起作用

a7qyws3x  于 2023-02-14  发布在  TypeScript
关注(0)|答案(1)|浏览(165)

我正在构建一个WebServer类,它将创建HTTP或HTTPS Express Web服务器。抽象类旨在为Express服务器设置一些默认值,扩展它的子类将根据服务器是http还是https添加一些设置。
但是我注意到在示例化服务器的时候,在抽象类中使用this.app.use(whateveroption)的时候,whateveroptionapp.use没有设置,在下面的例子中API路由器是不可访问的(调用端点是以超时结束的,helmet和morgan也没有设置,但是端点/isalive工作的很好,这里我错过了什么重要的东西吗?

已修复:我在this._app.use(express.json())中犯了拼写错误。键入this._app.use(express.json)而不是this._app.use(express.json())
抽象类

abstract class WebServer {
  private _app: Express;
  private _routers: IWebServerRoute[] = [];

  constructor() {
    this._applyDefaultToExpressApp();
  }

  private _applyDefaultToExpressApp() {
    this._app = express();
    this._app.get("/isalive", (_, res: Response) => res.status(200).json({ status: "I'm alive" })); // <== endpoint is OK
    const apiRouter = Router();
    apiRouter.get("/root", (_, res: Response) => res.status(200).json({ status: "from api root" }));
    this._app.use("/api", apiRouter); // <== timeout when calling localhost:5500/api/root
    this._app.use(express.json);
    this._app.use(
      express.urlencoded({
        extended: true,
      })
    );
    this._app.use(helmet());
    this._app.use(morgan("dev")); // <== no morgan logs in the console
  }

  public get app(): Express {
    return this._app;
  }

  abstract createWebServer(serverOptions: http.ServerOptions | https.ServerOptions): http.Server | https.Server;
}

HTTPWebServer子类

class HTTPWebServer extends WebServer {
  public server: http.Server;
  constructor(httpOptions?: THTTPWebServerOptions | undefined) {
    super();
  }
  public createWebServer(serverOptions?: http.ServerOptions | undefined): http.Server {
    if (serverOptions) {
      this.server = http.createServer(serverOptions, this.app);
    } else {
      this.server = http.createServer(this.app);
    }
    return this.server;
  }
}

用法示例

const webServer = new HTTPWebServer();
const server = webServer.createWebServer();
    
      server.listen(port, async () => {
        console.log(`server listen to ${port}`);
      });
gab6jxml

gab6jxml1#

修正:我在this._app.use(express.json())中犯了一个打字错误。输入了this._app.use(express.json)而不是this._app.use(express.json())

相关问题