英文:
AWS Lambda test event -> Cannot read properties of undefined (reading '0')
问题
以下是您要翻译的代码部分:
我有以下的lambda函数代码,使用GET http方法,试图从DynamoDB获取项目。使用AWS SDK v3
函数片段-
const { httpMethod, body, pathParameters } = event;
const { id } = pathParameters;
if (httpMethod === 'GET') {
// 读取操作
const params = {
TableName: 'Emp_Basic',
Key: { id }
};
const command = new GetItemCommand(params);
const result = await dynamoDBClient.send(command);
if (!result.Item) {
return {
statusCode: 404,
body: JSON.stringify({ message: '未找到项目' })
};
}
return {
statusCode: 200,
body: JSON.stringify(result.Item)
};
}
**我试图执行的测试事件,ID是使用uuidv4()生成的 -**
{
"httpMethod": "GET",
"body": "",
"pathParameters": {
"id": "f59fb118-6aa1-47fb-8f37-3d5b023feeea"
}
}
**我遇到的错误如下-**
{
"statusCode": 500,
"body": "{\"message\":\"处理请求时出错\",\"error\":\"无法读取未定义的属性(读取'0')\"}"
}
理论上,DynamoDB内部应该返回项目。无法弄清楚是什么原因引发了此问题
请注意,我已将HTML编码中的特殊字符(如&
和quot;
)还原为正常的字符,以便代码更易阅读。
英文:
I have the below lambda function code with GET httpmethod and trying to get an item from DynamoDB. Using AWS SDK v3
function snippet-
const { httpMethod, body, pathParameters } = event;
const { id } = pathParameters;
if (httpMethod === 'GET') {
// READ operation
const params = {
TableName: 'Emp_Basic',
Key: { id }
};
const command = new GetItemCommand(params);
const result = await dynamoDBClient.send(command);
if (!result.Item) {
return {
statusCode: 404,
body: JSON.stringify({ message: 'Item not found' })
};
}
return {
statusCode: 200,
body: JSON.stringify(result.Item)
};
}
The test event i'm trying to execute is, the id was generated using uuidv4() -
{
"httpMethod": "GET",
"body": "",
"pathParameters": {
"id": "f59fb118-6aa1-47fb-8f37-3d5b023feeea"
}
}
The error i'm getting is as follows-
{
"statusCode": 500,
"body": "{"message":"Error processing request","error":"Cannot read properties of undefined (reading '0')"}"
}
Ideally the item inside dynamodb should be returned. Not able to figure out whats causing this issue
答案1
得分: 2
问题在于您的代码不正确地指示了 Key
属性值,如下所示:
Key: { id }
相反,它需要指示键属性的名称、类型以及其值,具体如下:
Key: { id: { S: id } }
这表示了属性名称为 id
,类型为 S
(字符串)。
英文:
The problem is that your code indicates the Key
attribute value incorrectly, as:
Key: { id }
Instead, it needs to indicate both the name and the type of the key attribute, as well as its value, specifically:
Key: { id: { S: id } }
That indicates the attribute name of id
and the type of S
(string).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论