我是 AWS 的新手,當我嘗試將資料輸入到 dynamodb 并呼叫“API 網關”和“DynamoDB”之間的 lambda 函式時出現以下錯誤。
錯誤:
預期 params.Item['Age'].S 是一個字串............
錯誤截圖:

代碼:
我在瀏覽器(CodePen)中嘗試過(我使用了來自 API 網關的正確呼叫 URL):
var xhr = new XMLHttpRequest();
xhr.open('POST', 'The API Invoke URL');
xhr.onreadystatechange = function(event){
console.log(event.target.response);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({age: 26, height: 71, income: 2400}));
從 CodePen 運行上述代碼時,會呼叫以下 lambda 函式:
我已經正確匯入了aws-sdkand dynamodb。
exports.fn = (event, context, callback) => {
const params = {
Item: {
"UserId": {
S: "user_" Math.random()
},
"Age": {
N: event.age
},
"Height": {
N: event.height
},
"Income": {
N: event.income
}
},
TableName: "compare-yourself"
};
dynamodb.putItem(params, function(err, data) {
if (err) {
console.log(err);
callback(err);
} else {
console.log(data);
callback(null, data);
}
});
};
在上面的 lambda 函式中,您可以觀察到我已將輸入格式化為數字,但在 API 網關中,在 POST 集成請求中,我已將輸入轉換為字串。所以通過 lambda 函式傳遞的資料已經是一個字串。無需再通過 Lambda 函式進行格式化。
'POST Integration-Request' 中的正文映射器:
#set($inputRoot = $input.path('$'))
{
"age" : "$inputRoot.age",
"height": "$inputRoot.height",
"income": "$inputRoot.income"
}
我需要知道上述錯誤的原因,并且很樂意提供所需的任何其他資訊。
先感謝您。
uj5u.com熱心網友回復:
更改引數以指示年齡欄位的值是“字串”而不是“數字”:
const params = {
Item: {
"UserId": {
S: "user_" Math.random()
},
"Age": {
"S": event.age # This was previously set to "N" which causes the issue
},
"Height": {
N: event.height
},
"Income": {
N: event.income
}
},
TableName: "compare-yourself"
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/416658.html
標籤:
