Lambda中Serverless Express调用AWS Cognito创建用户超时求助
Serverless Express集成Lambda创建Cognito用户超时问题排查与修复
核心问题分析
你的Serverless Express代码存在两个关键问题,导致Lambda超时且用户创建失败:
1. Lambda入口未正确配置
纯Lambda函数直接导出handler处理APIGateway事件,但Serverless Express需要使用aws-serverless-express库的createHandler方法将Express应用转换为Lambda兼容的处理函数,否则Lambda无法正确解析请求,导致连接超时。
2. 路由中重复发送HTTP响应
在/api/v1/users/test路由的try/catch块中,即使catch已经返回500错误响应,后续代码仍会执行res.status(201).json(...),这会导致尝试重复发送响应,干扰请求处理流程。
修复后的完整代码
const express = require('express') const bodyParser = require('body-parser') const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware') const awsServerlessExpress = require('aws-serverless-express'); // 新增导入 const {CognitoIdentityProviderClient, AdminCreateUserCommand} = require("@aws-sdk/client-cognito-identity-provider"); const region = "us-east-1"; const userPoolId = "us-east-1_xxxxxx"; const cognitoClient = new CognitoIdentityProviderClient({region}); // declare a new express app const app = express() app.use(bodyParser.json()) app.use(awsServerlessExpressMiddleware.eventContext()) // Enable CORS for all methods app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*") res.header("Access-Control-Allow-Headers", "*") next() }); app.post('/api/v1/users/test', async function(req, res) { const createUserParams = { UserPoolId: userPoolId, // Replace with your User Pool ID Username: "dhara@testest.com", TemporaryPassword: "Dhara?123", UserAttributes: [ { Name: "email", Value: "dhara@testest.com", }, { Name: "preferred_username", Value: "Test", }, ], MessageAction: "SUPPRESS", }; try { console.log('try starts'); const response = await cognitoClient.send(new AdminCreateUserCommand(createUserParams)); console.log(response); // 成功后返回响应 res.status(201).json({ status:"success", user: response.User }); } catch (error) { console.error("Error creating user:", error); // 错误后返回,并用return终止后续代码执行 return res.status(500).json({ error: error.message || 'Failed to create user' }); } }); // 创建Lambda兼容的handler并导出 const server = awsServerlessExpress.createServer(app); exports.handler = (event, context) => { awsServerlessExpress.proxy(server, event, context); };
额外验证项
- 确认Lambda执行角色与纯Lambda函数拥有相同的权限,特别是
cognito-idp:AdminCreateUser权限 - 检查Cognito用户池ID是否正确(注意Serverless代码中的ID比纯Lambda少一位,可能是输入错误)
- 确保Lambda的超时时间设置足够(建议至少5秒,避免Cognito API调用超时)
内容的提问来源于stack exchange,提问作者Dhara
相关产品推荐
相关产品推荐

