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

NestJS API部署Azure静态Web应用后/api 404及入口点异常排查

问题:Azure Static Web Apps部署后/api路径返回404,NestJS API无法加载

问题背景

使用NX Monorepo管理Angular前端应用和NestJS后端API,通过GitHub Action部署到Azure Static Web Apps时,流水线显示构建部署成功,但访问应用时所有/api路径的请求均返回404。将NestJS代码直接部署到Azure Function时,出现入口点识别错误:

Result: Failure
Exception: Worker was unable to load function main: 'Unable to determine function entry point. If multiple functions are exported, you must indicate the entry point, either by naming it 'run' or 'index', or by naming it explicitly via the 'entryPoint' metadata property.'


解决方案

1. 适配NestJS到Azure Functions运行环境

Azure Functions无法直接识别原生NestJS的入口,需要做以下调整:

  • 安装NestJS的Azure Functions适配包:
    npm install @nestjs/azure-func-http --save
    
  • 修改NestJS的主入口文件(src/main.ts),改为Azure Functions兼容的格式:
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import { AzureHttpAdapter } from '@nestjs/azure-func-http';
    
    export async function run(context, req) {
      const app = await NestFactory.create(AppModule, new AzureHttpAdapter(context, req));
      await app.init();
      return app.handle(req);
    }
    
  • 在NestJS项目的根目录创建function.json,并配置到NX构建的资源列表中(确保构建时复制到dist/apps/api目录):
    {
      "bindings": [
        {
          "authLevel": "anonymous",
          "type": "httpTrigger",
          "direction": "in",
          "name": "req",
          "methods": ["get", "post", "put", "delete"],
          "route": "api/{*segments}"
        },
        {
          "type": "http",
          "direction": "out",
          "name": "$return"
        }
      ],
      "scriptFile": "./main.js",
      "entryPoint": "run"
    }
    
    (在NX的project.json中,给build任务添加assets配置,将function.json包含到输出目录)

2. 调整Azure Static Web Apps部署配置

  • 确认GitHub Action中的api_location指向正确的构建输出目录(dist/apps/api),且该目录包含function.json和编译后的NestJS代码。
  • 检查staticwebapp.config.json的路由规则,确保/api路径正确转发到后端:
    {
      "routes": [
        {
          "route": "/api/*",
          "rewrite": "/api"
        },
        {
          "route": "/*",
          "serve": "/index.html",
          "statusCode": 200
        }
      ]
    }
    

3. 查看API运行日志

在Azure Portal的Static Web Apps资源中,进入日志选项卡,选择函数日志,可以查看NestJS的启动和运行日志,确认API是否正常初始化。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 02:05:23