Nodejs express 不同文件中的路由 Express 对象自动转为 Router 对象

Nodejs express routes in different files Express object automatically turns into a Router object

我有一个带有 express 应用程序的 Nodejs。我使用 tsoa 注册我的路线。 当我将 swagger-ui-express 添加到我的 nodejs 应用程序时,出现以下错误 Error: TypeError: Router.use() requires a middleware function but got a undefined

我按如下方式初始化应用程序:

app.ts

  import config from './api/build/config';
    import express from 'express';
    
    
    function startServer() {
      const app = express();
    
      require('./api/loaders').default(app);
    
      app.listen(config.port, () => {
        console.log(`
          ################################################
          ️  Server listening on port: ${config.port}  ️ 
          ################################################
        `);
      });
    }
    
    startServer();

loaders\index.ts

import {Express} from 'express';

export default (app: Express) => {

  require('./express').default(app);
  console.log('✌️ Express loaded');

  require('./swagger').default(app);
  console.log('✌️ Swagger loaded');
};

express.ts

import bodyParser from 'body-parser';
import {Express, Request, Response, NextFunction} from 'express';
import logger from 'morgan';
import { RegisterRoutes } from '../routes';
import cors from 'cors';

export default function startExpress(app: Express) {
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(cors());

  //register all routes from the routes generated by tsoa
  RegisterRoutes(app);

  // catch 404 and forward to error handler
  app.use((request: Request, response: Response, next: NextFunction) => {
      const error = new Error('404 Not Found');
      error['status'] = 404; 
      next(error);
  });

// error handlers
// error handler will print stacktrace only in development
  app.use((error: any, request: Request, response: Response) => {
    response.locals.message = error.message;
    response.locals.error = request.app.get('env') === 'development' ? error : {};
    response.status(error.status || 500);
    response.send(error.message);
  });

}

swagger.ts

import { Express } from 'express';
import swaggerUi from 'swagger-ui-express';

export default function startSwagger(app: Express) {

    try{
        const swaggerDocument = require('../build/swagger.json');
        var options = {
          explorer: true
        };
        app.use('/swagger', swaggerUi.server, swaggerUi.setup(swaggerDocument, options));
    }
    catch(error){
        throw new Error(error);
    }

}

我也尝试过使用 import 语句来代替 require,但这并没有什么不同。为什么我的编译器突然说我的 app Express 对象是一个 Router 对象,我该如何设置 nodejs 的 express 并在不同的文件中注册路由?

回答你的问题...

Why does my compiler suddenly say my app Express object is a Router object...

没有。您可以看到对 Router.use() 函数的引用,因为它只是 eventually calledapp.use() 函数中。

错误消息中提到的实际问题是中间件函数未定义。这是因为在 swagger.ts 文件中,您将 swaggerUi.server 指定为中间件函数,但需要将其更改为 swaggerUi.serve.

import { Express } from 'express';
import swaggerUi from 'swagger-ui-express';

export default function startSwagger(app: Express) {

    try{
        const swaggerDocument = require('../build/swagger.json');
        var options = {
          explorer: true
        };
        // The problem was here... change server to serve
        app.use('/swagger', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
    }
    catch(error){
        throw new Error(error);
    }

}