如何通过Serverless Framework部署Node18版本NestJS到Azure Functions
Node 18环境下NestJS部署Azure Functions的Handler与serverless.yml配置方案
修正后的Handler代码
你之前的代码问题在于直接覆盖了context.res,且未正确让Nest的HTTP适配器接管请求响应流程。以下是适配Node 18的正确实现:
import { Context, HttpRequest } from '@azure/functions'; import { NestFactory } from '@nestjs/core'; import { ExpressAdapter } from '@nestjs/platform-express'; import * as express from 'express'; import { AppModule } from './app.module'; let cachedServer: express.Express | null = null; async function bootstrap(): Promise<express.Express> { const expressApp = express(); const adapter = new ExpressAdapter(expressApp); const app = await NestFactory.create(AppModule, adapter); // 按需启用CORS app.enableCors(); await app.init(); return expressApp; } export async function handler(context: Context, req: HttpRequest): Promise<void> { if (!cachedServer) { cachedServer = await bootstrap(); } // 适配Azure请求响应与Express模型 const expressReq = req as unknown as express.Request; const expressRes = { ...context.res, end: (body?: any) => { context.res.body = body; context.done(); }, } as unknown as express.Response; await new Promise<void>((resolve) => { cachedServer!(expressReq, expressRes, resolve); }); }
关键说明
- 用
ExpressAdapter显式绑定Express实例,确保和Azure Functions的请求响应模型兼容 - 缓存Express实例避免每次请求重复初始化Nest应用,提升性能
- 手动适配Azure的
context.res到Express响应对象,保证响应能正确返回给Azure平台
serverless.yml配置(适配Node 18)
service: nestjs-azure-functions frameworkVersion: '3' provider: name: azure runtime: nodejs18.x region: East US # 按需调整部署区域 environment: NODE_ENV: production functions: main: handler: dist/main.azure.handler # 对应编译后的handler文件路径 events: - http: true methods: - GET - POST - PUT - DELETE authLevel: anonymous # 按需调整认证级别 package: patterns: - '!node_modules/**' - '!.git/**' - '!src/**/*.spec.ts' excludeDevDependencies: true custom: azure: resourceGroup: nestjs-azure-functions-rg # 自定义资源组名称
配置要点
- 明确指定
runtime: nodejs18.x确保使用Node 18运行环境 handler路径指向编译后的文件(假设handler源码在src/main.azure.ts,编译后输出到dist/main.azure.js)package部分排除冗余文件,减小部署包体积
内容的提问来源于stack exchange,提问作者ganyavhad
相关产品推荐
相关产品推荐

