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

JavaScript Azure Function v4从Cosmos DB读取数据时挂起

Azure Functions + Cosmos DB模拟器挂起问题排查与解决

问题现象

  • 未添加Cosmos DB输入绑定的HTTP函数运行正常,能输出日志First id value is: 3
  • 添加Cosmos DB输入绑定后,函数触发后无任何日志输出,处理器代码未执行,出现挂起状态

正常运行代码

const { app } = require('@azure/functions');

app.http('httpTrigger', {
    methods: ['GET', 'POST'],
    handler: async (request, context) => {
        try {
            const Id = request.query.get('id');

            context.log(`First id value is: ${Id}`);

            return { body: `Response id =${Id}` };

        } catch (error) {
            context.log(`Error: ${error}`);
            return { status: 500, body: 'Internal Server Error' };
        }
    }
});

local.settings.json配置

{
  "IsEncrypted": false,
  "Values": {
    "FUNCTIONS_WORKER_RUNTIME": "node",
    "AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "CosmosDBConnectionString":"AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
  }
}

出现问题的代码

const { app, input } = require('@azure/functions');

const cosmosInput = input.cosmosDB({
    
    databaseName: 'my-database',
    containerName: 'my-container',
    connection: 'CosmosDBConnectionString',
    sqlQuery: 'SELECT * FROM c'
});

app.http('httpTrigger', {
    methods: ['GET', 'POST'],
    authLevel: 'anonymous',
    extraInputs: [cosmosInput],
    handler: async (request, context) => {
        try {
            const Id = request.query.get('id');

            context.log(`First id value is: ${Id}`);

            const toDoItem = context.extraInputs.get(cosmosInput);

            context.log(`Second id value is: ${Id}`);

            return { body: `Response id =${Id}` };

        } catch (error) {
            context.log(`Error: ${error}`);
            return { status: 500, body: 'Internal Server Error' };
        }
    }
});

排查与解决步骤

  1. 确认Cosmos DB模拟器状态

    • 确保模拟器正在运行,访问https://localhost:8081/_explorer/index.html能正常打开
    • 检查模拟器中是否已创建my-database数据库和my-container容器,未创建则手动完成创建
  2. 验证连接字符串与权限

    • 确认CosmosDBConnectionString无拼写错误,模拟器默认端口为8081,密钥为配置中的默认值,无需修改
    • 若模拟器曾重置过密钥,需同步更新配置中的AccountKey
  3. 调整输入绑定配置

    • 限制查询返回数据量:将sqlQuery改为SELECT TOP 5 * FROM c,避免全量查询返回过多数据导致超时挂起
    • 若容器设置了分区键,需在绑定中添加partitionKey参数(例如容器分区键为/id,则添加partitionKey: '{id}')
  4. 代码层面优化与错误捕获

    • 在获取Cosmos DB数据的逻辑外层单独添加异常捕获,便于定位绑定阶段的错误
    • 示例修改代码:
      const { app, input } = require('@azure/functions');
      
      const cosmosInput = input.cosmosDB({
          databaseName: 'my-database',
          containerName: 'my-container',
          connection: 'CosmosDBConnectionString',
          sqlQuery: 'SELECT TOP 5 * FROM c'
      });
      
      app.http('httpTrigger', {
          methods: ['GET', 'POST'],
          authLevel: 'anonymous',
          extraInputs: [cosmosInput],
          handler: async (request, context) => {
              try {
                  const Id = request.query.get('id');
                  context.log(`First id value is: ${Id}`);
      
                  let toDoItem;
                  try {
                      toDoItem = context.extraInputs.get(cosmosInput);
                      context.log(`Cosmos DB retrieved ${toDoItem?.length || 0} items`);
                  } catch (cosmosErr) {
                      context.log(`Cosmos binding error: ${cosmosErr.message}`);
                      return { status: 500, body: `Cosmos DB access failed: ${cosmosErr.message}` };
                  }
      
                  context.log(`Second id value is: ${Id}`);
                  return { body: `Response id =${Id}, Cosmos items count: ${toDoItem?.length || 0}` };
              } catch (error) {
                  context.log(`General error: ${error}`);
                  return { status: 500, body: 'Internal Server Error' };
              }
          }
      });
      
  5. 检查宿主日志与依赖版本

    • 查看Functions宿主终端的输出日志,绑定阶段的错误(如连接失败、容器不存在)会在这里输出,而非函数代码日志
    • 更新@azure/functions包到最新稳定版:执行npm install @azure/functions@latest,避免版本兼容问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 15:48:13