即使在 Nestjs 应用程序中启动服务器,Swagger 也无法工作

问题描述 投票:0回答:1

我设计了这个 main.ts 文件,需要使用 Swagger 测试控制器。我启动:dev,所有服务器工作正常,但无法通过 localhost:3000/docs/ws 访问进入 Swagger UI。这是代码:

//imported stuffs

async function docApi(app: NestExpressApplication) {
  const pathModule = {
    'docs/auth': AuthModule,
    'docs/client': ClientDomainModule,
    'docs/health': HealthModule,
    'docs/ws': WorkspaceModule,
  };

  const config = new DocumentBuilder()
    .setTitle('Booking API Documentation')
    .setDescription('Booking API Documentation')
    .setVersion('1.0')
    .addBearerAuth()
    .build();
  const css = await fs.readFileSync(pathLib.join(__dirname, '..', 'assets/css/swagger.css'), {
    encoding: 'utf8',
  });
  for (const [path, module] of Object.entries(pathModule)) {
    const document = SwaggerModule.createDocument(app, config, {
      deepScanRoutes: true,
      include: [module],
    });
    fs.writeFileSync(pathLib.join(__dirname, `./../${path}.sw.json`), JSON.stringify(document)); // <-- Save document to json file
    SwaggerModule.setup(path, app, document, {
      customCss: css,
      customSiteTitle: 'Booking API Documentation',
      customfavIcon: `http://${configApp.appUrl}:${configApp.port}/images/asd.ico`,
    });
  }
}

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  app.useGlobalPipes(new ValidationPipe({ whitelist: true }));

  app.enableCors();
  app.useStaticAssets(pathLib.join(__dirname, '..', 'assets'));
  const docUsers = {};
  docUsers[configDoc.username] = configDoc.password;
  app.use(
    // Paths you want to protect with basic auth
    '/docs*',
    basicAuth({
      challenge: true,
      users: docUsers,
    })
  );
  await docApi(app);
  const port = parseInt(process.env.PORT, 10) || 3000;
  await app.listen(port);
}

bootstrap();

我该如何解决这个问题,或者我输入了错误的路径来进入swagger?请帮忙

nestjs swagger swagger-ui nestjs-swagger
1个回答
0
投票

这是我在 main.ts 中的设置片段:

 const config = new DocumentBuilder()
      .setTitle('API DOCS')
      .setDescription('REST API Documentation')
      .setVersion('1.0')
      .addBearerAuth()
      .build();
    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('api', app, document, {
      jsonDocumentUrl: 'api/json-spec',
      yamlDocumentUrl: 'api/yaml-spec',
      customSiteTitle: 'API DOCS',
    });

其中

app
在您的情况下是
const app = await NestFactory.create<NestExpressApplication>(AppModule);

然后,我可以访问位于

http:localhost:3000/api
的 swagger 文档、位于
JSON spec
http:localhost:3000/api/json-spec
以及位于
http:localhost:3000/api/yaml-spec
的 YAML 规范。

我不确定为什么你需要将你的实现抽象为一个函数。

© www.soinside.com 2019 - 2024. All rights reserved.