You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure HTTP Trigger + NestJS环境下Swagger UI加载失败求助

解决Azure HTTP Trigger函数中Swagger静态资源Pending问题

问题原因

Azure Functions的HTTP触发器采用单请求处理模型,默认每次请求都会重新初始化Nest应用实例。Swagger UI依赖的静态资源(如swagger-ui.css、swagger-ui-bundle.js)需要稳定的服务端响应,重复创建应用实例会导致这些资源请求无法被正确处理,从而处于pending状态。

解决方案

通过缓存Nest应用实例,避免每次请求都重新初始化,确保静态资源请求能被持续响应。

修改后的配置代码

import { DtoValidationError } from '@class/dto-validator-error.class';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { ValidationError } from 'class-validator';
import { AppModule } from './app.module';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { Context, HttpRequest } from '@azure/functions';
import { AzureHttpAdapter } from '@nestjs/azure-func-http';

let cachedApp: INestApplication; // 缓存应用实例,避免重复初始化

export async function createApp(): Promise<INestApplication> {
    // 如果已有缓存的应用实例,直接返回
    if (cachedApp) {
        return cachedApp;
    }
    
    const app = await NestFactory.create(AppModule);
    app.setGlobalPrefix('api/project');

    const config = new DocumentBuilder()
      .setTitle('API')
      .setDescription('API PROJECT')
      .setVersion('1.0')
      .addServer('http://localhost:3000', 'Local Server')
      .build();

    const document = SwaggerModule.createDocument(app, config);
    SwaggerModule.setup('/swagger', app, document, {
        useGlobalPrefix: true
    });

    await app.init();
    cachedApp = app; // 缓存初始化完成的应用实例
    return app;
}

export default function(context: Context, req: HttpRequest): void {
  AzureHttpAdapter.handle(createApp, context, req);
}

额外检查项

  • 确认@nestjs/swagger与swagger-ui-express版本兼容(NestJS Swagger模块依赖该包提供静态资源服务)
  • 检查本地3000端口是否被其他进程占用,可通过netstat -ano | findstr :3000命令排查
  • 清理浏览器缓存后,重新访问http://localhost:3000/api/project/swagger

内容的提问来源于stack exchange,提问作者Khael Khael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 12:57:43